Home > Web Front-end > JS Tutorial > How to Preserve 'this' Context in setTimeout Callbacks?

How to Preserve 'this' Context in setTimeout Callbacks?

DDD
Release: 2024-12-26 16:15:09
Original
838 people have browsed it

How to Preserve

Passing the Correct "this" Context to setTimeout Callback

Question:

How can we execute a class method within a setTimeout callback function, preserving the context (i.e., "this") of the class?

Contextual Explanation:

When using setTimeout, the "this" variable refers to the global object (window), which is not the desired behavior when trying to access class properties or methods.

Answer:

Method 1: Storing a Local Reference

var that = this;
if (this.options.destroyOnHide) {
     setTimeout(function(){ that.tip.destroy() }, 1000);
}
Copy after login

Method 2: Using bind()

if (this.options.destroyOnHide) {
     setTimeout(function(){ this.tip.destroy() }.bind(this), 1000);
}
Copy after login

Method 3: Using Arrow Functions (ES6)

if (this.options.destroyOnHide) {
     setTimeout(() => { this.tip.destroy() }, 1000);
}
Copy after login

Method 4: Passing Arguments to setTimeout (HTML5)

if (this.options.destroyOnHide) {
     setTimeout(function(that){ that.tip.destroy() }, 1000, this);
}
Copy after login

Further Reading:

  • [setTimeout - The 'this' problem](https://qntm.org/blog/2009/05/the-this-problem)

The above is the detailed content of How to Preserve 'this' Context in setTimeout Callbacks?. For more information, please follow other related articles on the PHP Chinese website!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template