Home > Web Front-end > JS Tutorial > How to Correctly Access `this` in `setInterval` Handlers in JavaScript?

How to Correctly Access `this` in `setInterval` Handlers in JavaScript?

Mary-Kate Olsen
Release: 2024-12-01 05:49:13
Original
913 people have browsed it

How to Correctly Access `this` in `setInterval` Handlers in JavaScript?

Accessing this in setInterval Handlers in JavaScript

When using setInterval to schedule a function execution at a specified interval, it's often necessary to access the object that initiated the interval within the handler function. However, the this keyword inside the handler may not refer to the correct context, leading to errors.

Solution: Using bind

To ensure that the this keyword refers to the intended object within the setInterval handler, you can utilize the bind() method. As demonstrated in the code below:

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

By binding the retrieve_rate function to the current this context, the this keyword within the ajax.onload function will correctly point to the object that initiated the interval. This allows you to access the this.prefs property as desired.

The above is the detailed content of How to Correctly Access `this` in `setInterval` Handlers 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