![](/img/trans.png)
[英]How to reference a sibling property for use in property name declaration? [object literal, Javascript, es6]
[英]Reference nested 'sibling'-property in object literal
我想在同一个对象文字中的另一个属性中引用对象文字中的嵌套属性。
考虑以下人为的例子:
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.
}
}
}
以上显然是不正确的,但如何从'折扣'中获得'价格'和'price_was'?
我看了下面的问题,这个问题很接近,但在那个问题中,所需的属性是'this'的直接子项,在上面的例子中并非如此。 对象文字中的引用变量?
有什么办法吗?
“...在那个问题中,所需的财产是'这个'的直接子女,在上面的例子中并非如此”
事实上,它可能是,如果你打电话.discount()
从productN
对象。
所以,你不会用this.product1.price
,因为如果你打电话discount
从productN
,那么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
将会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.