Home > Article > Web Front-end > Handling \"this\" Reference in Prototype Methods with setInterval and setTimeout: What are the Solutions?
Handling this Reference in Prototype Methods with setInterval and setTimeout
In JavaScript, a prototype method loses its this association when extracted and passed elsewhere. Consider the following code:
function Foo() {} Foo.prototype = { bar: function () { this.baz(); }, baz: function () { this.draw(); requestAnimFrame(this.baz); } };
This code fails with an error because this is not properly bound inside the setInterval or setTimeout callbacks.
Solutions:
There are several ways to handle this issue:
Wrap Method Call in Anonymous Function:
var that = this; setInterval(function () { return that.baz(); }, 1000);
This preserves the this from the outer function using a helper variable.
Wrap Method Call in Fat Arrow Function:
setInterval(() => this.baz(), 1000);
Fat arrow anonymous functions maintain the this from the surrounding function.
Use a Binding Function:
setInterval(this.baz.bind(this), 1000); // dojo toolkit example: setInterval(dojo.hitch(this, 'baz'), 10);
Binding functions like Function.prototype.bind or library equivalents allow you to explicitly bind the this context.
The above is the detailed content of Handling \"this\" Reference in Prototype Methods with setInterval and setTimeout: What are the Solutions?. For more information, please follow other related articles on the PHP Chinese website!