简体   繁体   English

在对象文字中引用嵌套的'sibling'属性

[英]Reference nested 'sibling'-property in object literal

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'? 以上显然是不正确的,但如何从'折扣'中获得'价格'和'price_was'?

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. 我看了下面的问题,这个问题很接近,但在那个问题中,所需的属性是'this'的直接子项,在上面的例子中并非如此。 reference variable in object literal? 对象文字中的引用变量?

Any way to do this? 有什么办法吗?

"...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. 事实上,它可能是,如果你打电话.discount()productN对象。

So you wouldn't use this.product1.price , because if you're calling discount from productN , then this will be a reference to productN . 所以,你不会用this.product1.price ,因为如果你打电话discountproductN ,那么this将是一个参考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. 同样,这假设您正在从productN对象调用该函数。 If not, it would be helpful if you would show how discount is being called. 如果没有,如果您要显示如何调用discount将会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM