通过正确的“this"setTimeout 回调的上下文? [英] Pass correct "this" context to setTimeout callback?

查看:51
本文介绍了通过正确的“this"setTimeout 回调的上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将上下文传递到 setTimeout?如果 this.options.destroyOnHide 在 1000 毫秒后,我想调用 this.tip.destroy().我该怎么做?

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.

推荐答案

总之,早在 2010 年问这个问题时,解决这个问题的最常见方法是保存参考到 setTimeout 函数调用的上下文,因为 setTimeout 执行函数时 this 指向全局对象:

In summary, back in 2010 when this question was asked the most common way to solve this problem was 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);
} 

在一年前刚刚发布的 ES5 规范中,它引入了 bind 方法,这在最初的答案中没有被建议,因为它还没有得到广泛的支持,你需要 polyfills 来使用它,但现在它无处不在:

In the ES5 spec, just released a year before that time, it introduced the bind method, this wasn't suggested in the original answer because it wasn't yet widely supported and you needed polyfills to use it but now it's everywhere:

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

bind 函数使用预填充的 this 值创建一个新函数.

The bind function creates a new function with the this value pre-filled.

现在在现代 JS 中,这正是箭头函数在 ES6 中解决的问题:

Now in modern JS, this is exactly the problem arrow functions solve in ES6:

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

箭头函数没有自己的 this 值,当您访问它时,您正在访问封闭词法范围的 this 值.

Arrow functions do not have a this value of its own, when you access it, you are accessing the this value of the enclosing lexical scope.

HTML5 也 标准化计时器早在 2011 年,现在你可以将参数传递给回调函数:

HTML5 also standardized timers back in 2011, and you can pass now arguments to the callback function:

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

另见:

这篇关于通过正确的“this"setTimeout 回调的上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆