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

查看:25
本文介绍了通过正确的“这个"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.

推荐答案

总之,早在 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);
}

另见:

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

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