EDIT: 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:
(编辑:综上所述,早在2010年时,这一问题被提出来解决这个问题最常用的方法是将其保存到其中的上下文的引用setTimeout
函数调用时,因为setTimeout
执行与功能this
指向全局对象:)
var that = this;
if (this.options.destroyOnHide) {
setTimeout(function(){ that.tip.destroy() }, 1000);
}
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:
(在一年前发布的ES5规范中,它引入了bind
方法 ,但原始答案中并未建议这样做,因为该方法尚未得到广泛支持,您需要使用polyfills来使用它,但现在无处不在:)
if (this.options.destroyOnHide) {
setTimeout(function(){ this.tip.destroy() }.bind(this), 1000);
}
The bind
function creates a new function with the this
value pre-filled.
(bind
函数创建一个新函数,并预先填充this
值。)
Now in modern JS, this is exactly the problem arrow functions solve in ES6 :
(现在在现代JS中,这正是箭头函数在ES6中解决的问题:)
if (this.options.destroyOnHide) {
setTimeout(() => { this.tip.destroy() }, 1000);
}
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.
(箭头函数没有它自己的this
值,当您访问它时,您正在访问封闭的词法作用域的this
值。)
HTML5 also standardized timers back in 2011, and you can pass now arguments to the callback function:
(HTML5还在2011年对计时器进行了标准化 ,现在您可以将参数传递给回调函数:)
if (this.options.destroyOnHide) {
setTimeout(function(that){ that.tip.destroy() }, 1000, this);
}
See also:
(也可以看看:)