setInterval 与 (this)
请有人可以解释一下 setInterval 函数末尾的 (this) 的含义是什么:
function Klass(name) {
this.name = name;
this.handle = null;
this.startTimer = function() {
this.handle = setInterval(function(obj) {
return(function() {
alert(obj.name);
});
}(this), 5000); // <-------------------- (this)
}
Please, someone can explain me what is the meaning of (this) at the end of the function in a setInterval :
function Klass(name) {
this.name = name;
this.handle = null;
this.startTimer = function() {
this.handle = setInterval(function(obj) {
return(function() {
alert(obj.name);
});
}(this), 5000); // <-------------------- (this)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在构造中使用
this
的目的是为了在为执行的实际回调调用setInterval
时保留this
的含义在给定的间隔。如果没有手动保存,this
将在调用setInterval
时成为函数的所有者。这是关于这个主题的一篇非常好的文章
另一种可能更清晰的方法如下
The use of
this
in the construct is intended to preserve the meaning ofthis
at the pointsetInterval
is called for the actual call back that is executed at the given interval. Without the manual preservationthis
would become the owner of the function at the pointsetInterval
was called.Here's a very nice article on this subject
Another way this could be done which may be a bit clearer is the following