我是 Angular 2 的新手。想问一下如何在 startTimer() 中访问“task_title”。 我从 console.log() 得到的所有信息都是未定义的。我相信“this”指向函数本身,所以我无法获得“task_title”的值。
无论如何,我可以在嵌套函数中访问 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);
};
}
结果:未定义。
最佳答案
使用箭头函数或.bind(this)
来保留this
的范围
myTimer = setTimeout(this.startTimer.bind(this), 2000);
myTimer = setTimeout(() => this.startTimer(), 2000);
关于javascript - Angular 2 "this"无法访问嵌套函数中的全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38761986/