Huck Huck - 3 months ago 36
Javascript Question

Referencing "this" inside setInterval/setTimeout within object prototype methods

Normally I'd assign an alternative "self" reference when referring to "this" within setInterval. Is it possible to accomplish something similar within the context of a prototype method? The following code errors.

function Foo() {}
Foo.prototype = {
bar: function () {
baz: function () {


Unlike a language like Python a method forgets its a method after you extract it and pass it somewhere. You can either

Wrap the method call inside an anonymous function

This way, accessing the baz property and calling it happen at the same time, which is necessary for the this to be set correctly inside the method call.

Since the inner function has a different this from the outside, you need to use a helper variable.

var that = this;
    return that.baz();
}, 1000);

Wrap the method call inside a fat arrow function

Some Javascript implementations support arrow functions, which are anonymous functions that inherit the "this" from the outer function. If this ES6 feature is available for you, it is possible to make the previous solution a bit more succinct:

setInterval( (() => that.baz()), 1000 );

Use a binding function

A final alternative is to use a function such as Function.prototype.bind or an equivalent from your favorite Javascript library.

setInterval( this.baz.bind(this), 1000 );

//dojo toolkit example:
setInterval( dojo.hitch(this, 'baz'), 100);