gpt4 book ai didi

javascript - 将正确的 "this"上下文传递给 setTimeout 回调?

转载 作者:IT老高 更新时间:2023-10-28 13:13:39 25 4
gpt4 key购买 nike

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

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

当我尝试上述方法时,this 指的是窗口。

最佳答案

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

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

在一年前刚刚发布的 ES5 规范中,它引入了 bind method ,原始答案中没有建议这样做,因为它尚未得到广泛支持,并且您需要 polyfill 才能使用它,但现在它无处不在:

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

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

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

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

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

HTML5 也是 standardized timers早在 2011 年,您现在可以将参数传递给回调函数:

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

另见:

关于javascript - 将正确的 "this"上下文传递给 setTimeout 回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2130241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com