對象常量/初始化程序中的自引用 - Self-references in object literals / initializers

問題:

Is there any way to get something like the following to work in JavaScript? 有什麼辦法能夠使如下內容在JavaScript中起做用? this

var foo = {
    a: 5,
    b: 6,
    c: this.a + this.b  // Doesn't work
};

In the current form, this code obviously throws a reference error since this doesn't refer to foo . 在當前形式中,該代碼明顯拋出一個參考錯誤,由於this不是指foo But is there any way to have values in an object literal's properties depend on other properties declared earlier? 可是, 是否有任何方法能夠使對象文字的屬性值取決於先前聲明的其餘屬性? spa


解決方案:

參考一: https://stackoom.com/question/JMss/對象常量-初始化程序中的自引用
參考二: https://oldbug.net/q/JMss/Self-references-in-object-literals-initializers
相關文章
相關標籤/搜索