Home >Web Front-end >JS Tutorial >How to Preserve 'this' Context in setTimeout Callbacks?
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:
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!