传递正确的“这个”上下文setTimeout回调? [英] Pass correct "this" context to setTimeout callback?
本文介绍了传递正确的“这个”上下文setTimeout回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将上下文传递到 setTimeout
?我想在1000毫秒后调用 this.tip.destroy()
如果 this.options.destroyOnHide
如何做到这一点?
How do I pass context into setTimeout
? I want to call this.tip.destroy()
if this.options.destroyOnHide
after 1000 ms. How can I do that?
if (this.options.destroyOnHide) {
setTimeout(function() { this.tip.destroy() }, 1000);
}
当我尝试上述, this
指代窗口。
When I try the above, this
refers to the window.
推荐答案
您需要保存对 setTimeout
执行函数调用,因为 setTimeout
执行函数 this
全局对象:
You need to save a reference to the context where the setTimeout
function call is made, because setTimeout
executes the function with this
pointing to the global object:
var that = this;
if (this.options.destroyOnHide) {
setTimeout(function(){that.tip.destroy()}, 1000);
}
你可以很容易地证明 setTimeout
set
You can easily prove that setTimeout
set this
to the global object by:
(function () {
alert(this); // alerts hello
setTimeout(function(){
alert(this == window); // true
}, 1000);
}).call("hello");
另请参阅:
- setTimeout - The 'this' problem
这篇关于传递正确的“这个”上下文setTimeout回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文