我有以下代码,应该每秒显示一次递增的数字:
let timer_demo = {
count: 0,
timer: null,
update: function() {
this.count++;
console.log(this.count);
this.timer = setTimeout(this.update, 1000);
}
};
timer_demo.update();
但是,当我在 Chrome 中运行它时,我得到一个“1”,然后在一秒钟后得到一个“NaN”,然后什么也没有。计时器停止。我觉得问题在于我不理解在这种情况下“这个”是怎么回事。我只是不知道那是什么。第二次调用“update()”方法时,“count”字段为“NaN”这一事实似乎支持了这一断言。任何人都可以为我阐明这一点吗?
谢谢!
最佳答案
函数 setTimeout 不调用 this.update,而是获取更新函数的副本并重复它。不幸的是,它失去了与原始“this”的绑定(bind)。
要解决此问题,您可以执行以下操作:
let timer_demo = {
count: 0,
timer: null,
update: function() {
this.count++;
console.log(this.count);
this.timer = setTimeout(this.update.bind(this), 1000);
}
};
timer_demo.update();
这确保函数副本绑定(bind)到this。
关于javascript - 我想我误解了 JavaScript 中的 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45891530/