如何传递“this”到窗口setInterval [英] How to pass "this" to window setInterval
问题描述
假设我有一个函数a:
function a() {
this.b = 1;
this.set = setInterval(function() {console.log(this.b);}, 200);
}
因此,当调用a.set()时,将调用匿名函数。但是当这个函数被触发指向窗口对象时,这不会起作用。使用ab也不是一个好主意,因为可能有多个a的实例。
So when a.set() is called the anonymous function will be called. But this won't work as this at that time when the function is triggered points to the window object. Also it's not a good idea to use a.b as there may be multiple instances of a.
这个问题有什么好的解决方案?
What is a good solution to this problem?
推荐答案
存储对的引用
:
function a() {
var self = this;
self.b = 1;
self.set = setInterval(function() {console.log(self.b);}, 200);
}
您传递给 setInterval的匿名函数
可以访问其包含范围内的任何变量,即函数a()
的任何局部变量。即使在 a()
完成后,JS闭包的神奇之处仍然存在这些变量,并且每次调用 a()
得到自己的封闭。
The anonymous function that you pass to setInterval
has access to any variables in its containing scope, i.e., any local variables of function a()
. The magic of JS closures keeps these variables alive even after a()
has completed, and each invocation of a()
gets its own closure.
这篇关于如何传递“this”到窗口setInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!