Home > Web Front-end > JS Tutorial > How Can I Access the Correct Object Instance Within a `setInterval` Callback in JavaScript?

How Can I Access the Correct Object Instance Within a `setInterval` Callback in JavaScript?

Linda Hamilton
Release: 2024-11-29 20:33:10
Original
714 people have browsed it

How Can I Access the Correct Object Instance Within a `setInterval` Callback in JavaScript?

Accessing this from Within setInterval in JavaScript

When working with setInterval() in JavaScript, it can become challenging to access the correct instance of the object from within the callback function. This issue arises when the callback function is a method of the object, and the this keyword doesn't refer to the desired instance due to the way JavaScript handles event handling.

To overcome this limitation, let's explore a solution that utilizes the bind() method to bind the callback function to the correct object instance.

Consider the following example:

prefs: null,
startup : function()
    {
        // init prefs
        ...
        this.retrieve_rate();
        this.intervalID = setInterval(this.retrieve_rate, this.INTERVAL);
    },

retrieve_rate : function()
    {
        var ajax = null;
        ajax = new XMLHttpRequest();
        ajax.open('GET', 'http://xyz.example', true);
        ajax.onload = function()
        {
            // access prefs here
        }
    }
Copy after login

In this example, the goal is to access the prefs property of the object from within the onload handler of the AJAX request. However, the default behavior of JavaScript causes this to refer to the window object within the onload function.

To resolve this issue, we can use the bind() method to bind the retrieve_rate function to the current object instance. This ensures that when the onload function is invoked, the this keyword will refer to the correct object.

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

By modifying the code in this way, we ensure that this refers to the correct object instance when the onload function is called, allowing us to access the prefs property as desired.

The above is the detailed content of How Can I Access the Correct Object Instance Within a `setInterval` Callback in JavaScript?. 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