Will
Will

Reputation: 5590

setInterval - can I make it recognize "this"

I'm not even sure how to ask this question but I've pared down the code to the simplest possible example I could:

function Handler() {}
Handler.prototype.texts = [];
Handler.prototype.add = function(d) {
  this.texts.push(d);
};
Handler.prototype.tick = function() {
  console.log( this.texts );
};

var x = new Handler();
setInterval( x.tick, 5000 );

x.add('beatles');

when setInterval calls x.tick, it gives a value of undefined for this.texts - and, of course, for this. while I can solve the problem via

setInterval( x.tick, 5000, x );

// and ... in the prototype
Handler.prototype.tick = function(myObj) {
    console.log( myObj.texts );
}

It feels a bit clunky. Is there a better way to do this?

Upvotes: 1

Views: 59

Answers (2)

hvgotcodes
hvgotcodes

Reputation: 120258

make x an upvalue like so

setInterval(function(){
  x.tick()
}, 5000);

When setInterval fires, a closure will be created around the instance of x.

Upvotes: 5

Jamund Ferguson
Jamund Ferguson

Reputation: 17014

Use Function.prototype.bind

setInterval( x.tick.bind(x), 5000 );

There are working shims to support older browsers as well: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind

Upvotes: 3

Related Questions