Home >Web Front-end >JS Tutorial >How Can I Preserve the `this` Context in JavaScript's `setInterval` Callback?

How Can I Preserve the `this` Context in JavaScript's `setInterval` Callback?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-29 10:34:14282browse

How Can I Preserve the `this` Context in JavaScript's `setInterval` Callback?

Preserving this in JavaScript's setInterval Callback

In JavaScript, the this keyword refers to the object that owns the currently executing code. This can become problematic when using setInterval, as the callback function is executed in a different context, losing access to the original this. To overcome this:

Accessing this in setInterval Handlers

To allow access to this in the setInterval callback, we can use the bind() method:

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

Here, bind(this) ensures that the this within the retrieve_rate callback always refers to the object where the interval was set (i.e., the object where prefs is defined).

With this modification, you can now access this.prefs within the ajax.onload callback:

ajax.onload = function()
{
    // Access this.prefs here
}

The above is the detailed content of How Can I Preserve the `this` Context in JavaScript's `setInterval` Callback?. 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