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

标签 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.

      }
   }
} 

上面显然是不正确的,但是如何从'discount'中得到'price'和'price_was'呢?

我查看了以下问题,该问题很接近,但在该问题中所需的属性是“this”的直接子项,而在上面的示例中并非如此。 reference variable in object literal?

有什么办法吗?

最佳答案

"...in that question the needed property is a direct child of 'this', which in the above example isn't the case"

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

所以你不会使用 this.product1.price,因为如果你从 productN 调用 discount,那么 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 将会很有帮助。

关于javascript - 引用嵌套 'sibling' - 对象文字中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7408640/

相关文章:

javascript - 对象文字调用默认属性

javascript - 如何在 Node 脚本中重用 Angular 模块

javascript - 将 asp.net 控件作为参数传递给 javascript 函数

javascript - Select2 4.0 JSON 搜索不起作用

javascript - 创建对象后向其添加附加函数

javascript - 为什么有些对象文字属性被引用而有些则没有?

python - Python 是否支持文字对象之类的东西?

javascript - 如何使用 javascript 在我的 View 中重复特定的 C# 代码块,甚至应该这样做吗?

javascript - 使用 JavaScript 在 Firefox 中保存 HTML 页面

javascript - 使用 javascript 对象文字表示法定义函数