Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass "this" to window setInterval

Tags:

javascript

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?

like image 215
NSF Avatar asked Jun 08 '12 06:06

NSF


2 Answers

Store a reference to this:

function a() {
    var self = this;
    self.b = 1;
    self.set = setInterval(function() {console.log(self.b);}, 200);
}

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.

like image 175
nnnnnn Avatar answered Oct 17 '22 03:10

nnnnnn


Since we have ES6 now, I think we need another answer here:

Use an arrow function:

function a() {
  this.b = 1;
  this.set = setInterval(() => {console.log(this.b);}, 200);
}

Arrow functions, opposite to normal functions, don't have a this context on their own. This means you have access to the outer this.

like image 41
Lux Avatar answered Oct 17 '22 04:10

Lux