typescript - 函數內的類別變數未定義
只是想學習 Angular 2+(特別是 8),但無論我怎麼努力,都無法理解為什麼在類函數內類變量是『未定義』的,但如果我用 ES6 風格寫函數,就可以訪問它。
我試著改在建構函數中設定,但那沒有道理。
export class GameControlComponent implements OnInit {
myVar;
counter = 0;
constructor() {} ngOnInit() {}
handleClickStart() {
this.myVar = setInterval(this.myFunc, 1500);
}
myFunc() {
this.counter++;
console.log(this.counter);
}
}
一旦調用 'handleClickStart',這每 1.5 秒就會輸出 NaN。為什麼???我本以為會是 1 2 3…
以這種方式實作 handleClickStart 給了我理想的結果:
handleClickStart() {
this.myVar = setInterval(() => {
console.log(this.counter + 1);
this.counter++;
}, 1500);
}
但仍然無法弄清楚為什麼第一次沒有成功。
答案#1
這種行為與作用域、箭頭函數、this 以及 Javascript 函數/物件的運作方式有關。
JavaScript 中的函數在特定的上下文中運行,使用 this 可以訪問當前上下文。範例代碼中的 this.counter 在 setInterval() 函數內部不可用或未定義,因此我們得到 undefined。
現在,在箭頭函數中,情況有所特別/不同。箭頭函數總是詞法綁定上下文(詞法作用域意味著它使用包含箭頭函數的程式碼的this),因此this將會參考原始的上下文,即該類別。
一個更簡單的例子可能會使它更清楚。
const obj = {
myVar: 'foo',
myFunc: function() {
console.log('Actual Variable value: ',this.myVar)
setTimeout(() => {
console.log('Set timeout using Arrow function: ',this.myVar)
}, 1000);
setTimeout(function () {
console.log('Set timeout using Normal function: ',this.myVar)
}, 1000);
}
}
obj.myFunc();
輸出
Actual Variable value: foo
Set timeout using Arrow function: foo
Set timeout using Normal function: undefined
閱讀更多
- 箭頭函數
- 這個關鍵字
