在对象字面量中引用嵌套的“sibling”属性

发布于 2024-12-04 07:47:47 字数 697 浏览 0 评论 0原文

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

考虑以下人为的示例:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

濫情▎り 2024-12-11 07:47:47

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

实际上,如果您调用,则可能是这样来自 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,将会很有帮助。

"...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.

So you wouldn't use this.product1.price, because if you're calling discount from productN, then this will be a reference to 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. If not, it would be helpful if you would show how discount is being called.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文