[英]How to reference a sibling property for use in property name declaration? [object literal, Javascript, es6]
[英]Reference nested 'sibling'-property in 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.
}
}
}
以上顯然是不正確的,但如何從'折扣'中獲得'價格'和'price_was'?
我看了下面的問題,這個問題很接近,但在那個問題中,所需的屬性是'this'的直接子項,在上面的例子中並非如此。 對象文字中的引用變量?
有什么辦法嗎?
“...在那個問題中,所需的財產是'這個'的直接子女,在上面的例子中並非如此”
事實上,它可能是,如果你打電話.discount()
從productN
對象。
所以,你不會用this.product1.price
,因為如果你打電話discount
從productN
,那么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
將會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.