Pass correct quot;thisquot; context to setTimeout callback?(通过正确的“thissetTimeout 回调的上下文?)
问题描述
如何将上下文传递到 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);
}
另见:
- setTimeout - 'this' 问题
这篇关于通过正确的“this"setTimeout 回调的上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通过正确的“this"setTimeout 回调的上下文?
基础教程推荐
- 在for循环中使用setTimeout 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 动态更新多个选择框 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01