Home > Web Front-end > JS Tutorial > body text

Handling \'this\' Reference in Prototype Methods with setInterval and setTimeout: What are the Solutions?

Linda Hamilton
Release: 2024-10-18 15:03:30
Original
367 people have browsed it

Handling

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);
  }
};
Copy after login

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);
Copy after login

This preserves the this from the outer function using a helper variable.

Wrap Method Call in Fat Arrow Function:

setInterval(() => this.baz(), 1000);
Copy after login

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);
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template