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?
Use
Function.prototype.bindThere are working shims to support older browsers as well:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind