Suppose I have a function a:
function a() {
this.b = 1;
this.set = setInterval(function() {console.log(this.b);}, 200);
}
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?
Store a reference to
this:The anonymous function that you pass to
setIntervalhas access to any variables in its containing scope, i.e., any local variables offunction a(). The magic of JS closures keeps these variables alive even aftera()has completed, and each invocation ofa()gets its own closure.