2016-08-04 37 views
1

我對Angular 2很陌生。想問我如何訪問startTimer()中的「task_title」。 我從console.log()得到的所有內容都是未定義的。我相信「這個」是指向函數本身,所以我不能得到「task_title」的價值。Angular 2「this」無法訪問嵌套函數中的全局變量

是否有無論如何我可以訪問嵌套函數中的Typescript全局變量?

export class DashboardComponent { 

    task_title: string; 

    myTimer = setTimeout(this.startTimer, 2000); 

    updateTask(event: any){ 
     clearTimeout(this.myTimer); 
     this.task_title = event.target.value; 
     this.myTimer = setTimeout(this.startTimer, 2000); 
    } 

    startTimer() { 
     console.log(this.task_title); 
     this.myTimer = setTimeout(this.startTimer, 2000); 
    }; 
} 

結果:未定義。

回答

6

使用箭頭功能或.bind(this)保留的this

myTimer = setTimeout(this.startTimer.bind(this), 2000); 
myTimer = setTimeout(() => this.startTimer(), 2000); 
+0

它的工作原理!謝謝您的幫助 :) – Danzeeeee

1

這就像變種自用參考範圍=該

export class DashboardComponent { 

var self=this; 


task_title: string; 

myTimer = setTimeout(self.startTimer, 2000); 

updateTask(event: any){ 
    clearTimeout(self.myTimer); 
    self.task_title = event.target.value; 
    self.myTimer = setTimeout(self.startTimer, 2000); 
} 

startTimer() { 
    console.log(self.task_title); 
    self.myTimer = setTimeout(self.startTimer, 2000); 
}; 
}