我想从同一对象字面量中的另一个属性中引用对象字面量中的嵌套属性。
考虑以下人为的示例:
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.
}
}
}
上面显然是不正确的,但是如何从'discount'中得到'price'和'price_was'呢?
我查看了以下问题,该问题很接近,但在该问题中所需的属性是“this”的直接子项,而在上面的示例中并非如此。 reference variable in object literal?
有什么办法吗?
最佳答案
"...in that question the needed property is a direct child of 'this', which in the above example isn't the case"
实际上,如果您从 productN
对象调用 .discount()
可能是这样。
所以你不会使用 this.product1.price
,因为如果你从 productN
调用 discount
,那么 this
将是对 productN
的引用。
只需这样做:
this.price;
this.price_was;
...所以它看起来像:
var obj = {
product1: {
price: 80,
price_was: 100,
discount: function(){
return 100 - (100 * (this.price/this.price_was));
}
}
};
同样,这假定您从 productN
对象调用该函数。如果没有,如果您能展示如何调用 discount
将会很有帮助。
关于javascript - 引用嵌套 'sibling' - 对象文字中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7408640/