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
Linda HamiltonOriginal
2024-12-06 02:58:13337browse

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);

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
}

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!

Statement:
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