Reference nested 'sibling'-property in object literal

大兔子大兔子 提交于 2019-12-08 17:28:38

问题


I want to reference a nested property in an object literal from within another property in that same object literal.

Consider the following contrived example:

var obj = {
   product1: {
      price: 80,
      price_was: 100,
      discount: function(){

        return 100 - (100 * (price/price_was));

        //I don't want to use:  
        //100 - (100 * (this.product1.price/this.product1.price_was))
        //because the name of the parent ('product1' in this case) isn't known 
        //a-priori.

      }
   }
} 

The above is obviously incorrect, but how to get to 'price' and 'price_was' from within 'discount'?

I've looked at the following question, which is close, but in that question the needed property is a direct child of 'this', which in the above example isn't the case. reference variable in object literal?

Any way to do this?


回答1:


"...in that question the needed property is a direct child of 'this', which in the above example isn't the case"

Actually, it probably is if you're calling .discount() from the productN object.

So you wouldn't use this.product1.price, because if you're calling discount from productN, then this will be a reference to productN.

Just do this:

this.price;
this.price_was;

...so it would look like:

var obj = {
   product1: {
      price: 80,
      price_was: 100,
      discount: function(){

        return 100 - (100 * (this.price/this.price_was));

      }
   }
};

Again, this assumes you're calling the function from the productN object. If not, it would be helpful if you would show how discount is being called.



来源:https://stackoverflow.com/questions/7408640/reference-nested-sibling-property-in-object-literal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!