Home > Web Front-end > JS Tutorial > How Can I Access `this` Correctly Inside a JavaScript `setInterval` Handler?

How Can I Access `this` Correctly Inside a JavaScript `setInterval` Handler?

Linda Hamilton
Release: 2024-12-06 02:58:13
Original
371 people have browsed it

How Can I Access `this` Correctly Inside a JavaScript `setInterval` Handler?

Accessing this from a JavaScript setInterval Handler

When using setInterval in JavaScript, it can be challenging to access the object instance (this) within the handler function. This is because setInterval creates a new context for the handler function.

To resolve this issue, we can bind the handler to the object instance, ensuring that it has access to the this keyword. Here's how:

this.intervalID = setInterval(this.retrieve_rate.bind(this), this.INTERVAL);
Copy after login

In this modified code, the bind method is used to create a new function that is bound to the current object instance. This function is then passed as the handler to setInterval.

Within the retrieve_rate handler function, you now have access to the this keyword and can use it to access the prefs property:

retrieve_rate: function() {
  // access prefs here
  // this.prefs
}
Copy after login

The above is the detailed content of How Can I Access `this` Correctly Inside a JavaScript `setInterval` Handler?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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