Unlike a language such as Python, the Javascript method forgets that it is a method after retrieving it and passing it elsewhere. You can either
Wrap a method call inside an anonymous function
Thus, access to the baz property and its call occurs at the same time, which is necessary for correctly setting this inside the method call.
You will need to store this from the external function in a helper variable, since the internal function will refer to another this object.
var that = this; setInterval(function(){ return that.baz(); }, 1000);
Wrap a method call inside the thick arrow function
In Javascript implementations that implement the arrow function of a function , you can write the above solution in a more concise way using the fat arrow syntax:
setInterval( () => this.baz(), 1000 );
Fat arrow's anonymous functions save this from the surrounding function, so there is no need to use the var that = this trick. To find out if you can use this function, refer to the compatibility table, for example this one .
Use the snap function
The ultimate alternative is to use a function like Function.prototype.bind or the equivalent from your favorite JavaScript library.
setInterval( this.baz.bind(this), 1000 ); //dojo toolkit example: setInterval( dojo.hitch(this, 'baz'), 100);
source share