10

我想从同一对象文字中的另一个属性中引用对象文字中的嵌套属性。

考虑以下人为设计的示例:

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”的直接子级,在上面的示例中并非如此。 对象文字中的引用变量?

有什么办法可以做到这一点?

4

1 回答 1

4

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

实际上,可能是您.discount()productN对象调用。

所以你不会使用this.product1.price,因为如果你调用discountfrom productN, thenthis将是对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被调用,将会很有帮助。

于 2011-09-13T21:24:28.107 回答