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

Gee*_*Jan 7 javascript 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.

      }
   }
} 
Run Code Online (Sandbox Code Playgroud)

以上显然是不正确的,但如何从'折扣'中获得'价格'和'price_was'?

我看了下面的问题,这个问题很接近,但在那个问题中,所需的属性是'this'的直接子项,在上面的例子中并非如此. 对象文字中的引用变量?

有什么办法吗?

use*_*716 4

“...在这个问题中,所需的属性是“this”的直接子属性,但在上面的示例中并非如此”

.discount()实际上,如果您从对象调用,则可能是这样productN

所以你不会使用this.product1.price,因为如果你discount从调用productN,那么this将是对 的引用productN

只需这样做:

this.price;
this.price_was;
Run Code Online (Sandbox Code Playgroud)

...所以它看起来像:

var obj = {
   product1: {
      price: 80,
      price_was: 100,
      discount: function(){

        return 100 - (100 * (this.price/this.price_was));

      }
   }
};
Run Code Online (Sandbox Code Playgroud)

同样,这假设您正在从对象调用该函数productN如果没有,如果您能说明如何 discount被调用,将会很有帮助。