亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在計算屬性名稱中解釋關鍵字“this”?

如何在計算屬性名稱中解釋關鍵字“this”?

慕蓋茨4494581 2022-07-21 10:19:16
考慮以下兩個示例。var obj1 = {    "a": "A",    "b": "B",    [this.a + this.b]: function(a) {return a + this.a}};console.log(obj1.AB("a"))//TypeError: obj1.AB is not a function  var obj2 = {    "a": "A",    "b": "B",    "AB": function(a) {return a + this.a}};  console.log(obj2.AB("a"))//aA  第一個示例中出現錯誤的原因是什么?如果關鍵字“this”出現在計算屬性名稱中,它如何解釋?
查看完整描述

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


查看完整回答
反對 回復 2022-07-21
?
嗶嗶one

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”的值。


查看完整回答
反對 回復 2022-07-21
?
喵喵時光機

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"));


查看完整回答
反對 回復 2022-07-21
  • 3 回答
  • 0 關注
  • 165 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號