3 回答

TA貢獻1790條經驗 獲得超9個贊
如果您查看計算屬性名稱
您可以看到您可以在括號內放置一個表達式,這可能會導致以下構造 [(console.log(x),x)]返回x,但允許我們轉儲它之前保存的內容。
const a = {
[(console.log('log:', this.a + this.b), this.a + this.b)]: 'test'
}
// this.a is undefined and summing them is NaN
console.log(a.NaN) // 'test'
如果我們現在考慮下面
;(function () {
const a = {
[(console.log('log', this.a + this.b), this.a + this.b)]: 'top'
}
console.log(a.zz) // 'top'
}).call({ a: 'z', b: 'z' })
我們確實得到了一些 zztop。
我還沒有閱讀所有規范,但在某種程度上我們可能會依賴正在運行的執行上下文來確定this
第一種情況:全球環境
在后面:已綁定的函數{a: 'z', b: 'z'}
因為我們有點貪心:
window.a = 'z'
window.b = 'z'
const c = {
[(console.log('log', this.a + this.b), this.a + this.b)]: 'test'
}
console.log(c.zz) // 'test'
編輯:關于this函數中的。它與用于計算屬性名稱的表達式無關,并且過著它的生活this
const a = {
hello: 'top',
zz: function () { console.log(this.hello) } // top
}
a.zz()
// the first this is resolved as the global env
// the this in function is resolved as b
const b = {
hello: 'top',
[(console.log('the this.hello is undef', this.hello), 'zz')]: function () { console.log(this.hello) } // top. The caller is b.
}
b.zz()
// and some usual invocation where this is bound to a
const c = {
hello: true,
['zz']: function () { console.log(this.hello) } // top
}
a.hello = 'TOP'
c.zz.call(a) // TOP

TA貢獻1854條經驗 獲得超8個贊
首先,我們不應該像這樣創建 JS 對象的屬性:
[this.a + this.b]: function(a) {return a + this.a}.
左側必須是主叫名稱。另一方面, 的值this
取決于函數的調用方式(運行時綁定)。執行時不能通過賦值來設置,每次調用函數時可能都不一樣。在第二個例子中:
"AB": function(a) {return a + this.a}
在這里,您調用了 return a(這將是傳遞給函數的參數)+ this.a。這里 this 指的是 obj2 及其屬性“a”的值。

TA貢獻1846條經驗 獲得超7個贊
您不能像這樣分配鍵
不,如果您檢查下面的代碼,您可以看到您的功能鍵是 NaN
您正在嘗試添加兩個未定義的鍵,這就是它顯示的原因NaN
請記住它Object不是constructor
var obj1 = {
"a": "A",
"b": "B",
[this.a + this.b]: function(a) { return a + this.a }
};
console.log(obj1);
現在要解決您的問題,您可以
首先創建對象并添加 foo
var obj1 = {
a: "A",
b: "B",
};
obj1[obj1.a + obj1.b] = function(a) { return a + this.a };
console.log(obj1.AB("a"));
添加回答
舉報