在对象字面量中引用嵌套的“sibling”属性
我想从同一对象文字中的另一个属性引用对象文字中的嵌套属性。
考虑以下人为的示例:
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”的直接子级,而在上面的示例中并非如此。 对象文字中的引用变量?
有什么方法可以做到这一点吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上,如果您调用
,则可能是这样来自
。productN
对象的 .discount()因此,您不会使用
this.product1.price
,因为如果您从productN
调用discount
,则this 将是对
productN
的引用。只需这样做:
...所以它看起来像:
再次,这假设您从
productN
对象调用该函数。如果没有,如果您能显示如何调用discount
,将会很有帮助。Actually, it probably is if you're calling
.discount()
from theproductN
object.So you wouldn't use
this.product1.price
, because if you're callingdiscount
fromproductN
, thenthis
will be a reference toproductN
.Just do this:
...so it would look like:
Again, this assumes you're calling the function from the
productN
object. If not, it would be helpful if you would show howdiscount
is being called.