javascript - Angular 2 "this"无法访问嵌套函数中的全局变量

标签 javascript angularjs function typescript angular

我是 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/

相关文章:

javascript - 在 Javascript 中为全局变量添加属性

node.js - NPM 更新和清理后 Grunt 构建不起作用

javascript - 为什么我的 If 语句在 AngularJS 中的 JS 中不能 100% 工作

json - 如何创建一个将 json 字符串转换为 golang 结构的通用函数?

c++ - 当我们使用斐波那契数列的递归方法调用 fib(6) 时,fib(3) 被调用多少次?

javascript - 如何在for循环中执行多个let

javascript - Android 版 Chrome 在重放录音时出现错误

javascript - 测量文本宽度/高度而不渲染

javascript - 更新本地存储中数组中的项目

r - 不同R函数之间的PCA值不同,有什么解释吗?