Link nested 'sibling'-property in the object literal

I want to reference a nested property in an object literal from another property in the 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 not true, but how do I get to the "price" and "your_price" from the "discount"?

I examined the following question, which is close, but in this question, the required property is a direct child of 'this', which is not the case in the above example. reference variable in object literal?

How to do it?

+6
source share
1 answer

"... in this question, the required property is a direct descendant of 'this', which is not the case in the above example"

Actually, maybe you are calling .discount() from the productN object.

Therefore, you would not use this.product1.price , because if you call discount from productN , then this will be a link to productN .

Just do the following:

 this.price; this.price_was; 

... so it will look like this:

 var obj = { product1: { price: 80, price_was: 100, discount: function(){ return 100 - (100 * (this.price/this.price_was)); } } }; 

Again, it is assumed that you are calling a function from the productN object. If not, it would be useful if you showed how discount is called.

+3
source

Source: https://habr.com/ru/post/897268/


All Articles