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

How to Preserve 'this' Context in setTimeout Callbacks?

DDD
DDDOriginal
2024-12-26 16:15:09769browse

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

Method 2: Using bind()

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

Method 3: Using Arrow Functions (ES6)

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

Method 4: Passing Arguments to setTimeout (HTML5)

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

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