[英]I think I'm misunderstanding “this” in JavaScript
我有以下代码应该每秒显示一个递增数字:
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”,然后什么也没有。 计时器停止。 我感到问题在于我在这种情况下不了解“ this”的含义。 我只是不知道那是什么。 第二次调用“ update()”方法时,“ count”字段为“ NaN”的事实似乎支持了该断言。 有人可以帮我一下吗?
谢谢!
函数setTimeout不调用this.update,而是获取update函数的副本并重复执行。 不幸的是,它失去了与原始“ this”的绑定。
要变通解决此问题,您可以执行以下操作:
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();
这样可以确保函数副本已绑定到this 。
var timer_demo = {
count: 0,
timer: null,
update: function() {
console.log(this);
this.count++;
console.log(this.count);
this.timer = setTimeout(this.update.bind(this), 1000);
}
};
timer_demo.update();
在setTimeout回调中,默认情况下(非严格模式下) 这是窗口对象。 要将自定义传递给setTimeout回调,请使用bind。
为了更好地理解javascript,请阅读http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/ 。
您可以使用新的箭头功能来处理此问题。 他们不绑定自己的this
,因此您最终将无法从外部环境获得它。
let timer_demo = {
count: 0,
timer: null,
update: () => {
this.count++;
console.log(this.count);
this.timer = setTimeout(this.update, 1000);
}
};
timer_demo.update();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.