2017-09-24 78 views
0

我有一個屬性已定義,但是當我嘗試從setInterval匿名函數中訪問它時,它不被識別。「this」在函數內部不被識別

this.game.seconds = 6; 
    useTimer() { 
    let timer = setInterval(
     function() { 
     this.game.seconds--;//here the keyword this is not being recognized 
     }, 1000 
    ); 
    } 
+2

可能重複[如何「this」關鍵字工作?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) –

+1

提示:這是因爲你是**不**使用箭頭功能 – Dummy

+0

這與TypeScript無關。您正在編程的語言被稱爲「JavaScript」。 TypeScript只是JavaScript上的一個簡單的輸入層。 TypeScript沒有爲'this'引入新的語義。的確,它沒有引入任何新的執行語義。 – 2017-09-24 07:26:05

回答

1

的問題時,因爲你不是用箭頭功能。

箭頭函數從外部執行上下文中取出this

ref該提到:

箭頭功能,這確實提供了他們自己的這種結合(它仍然是 包圍詞彙上下文的此值)。

閱讀更多的No Binding of this

所以只是爲了這個:

let timer = setInterval(
() => { 
    this.game.seconds--; // 'this' takes its value from the outer context 
    }, 1000 
); 
0

嗯,我能完成我的目標與由假評論,並回答了gsamaras箭頭功能:

this.game.seconds = 6; 
    useTimer() { 
    let timer = setInterval(
    () => { 
     this.game.seconds--; 
     }, 1000 
    ); 
    } 

更多信息here