Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
462 views
in Technique[技术] by (71.8m points)

javascript - 将正确的“ this”上下文传递给setTimeout回调? [重复](Pass correct “this” context to setTimeout callback? [duplicate])

This question already has an answer here:

(这个问题已经在这里有了答案:)

How do I pass context into setTimeout ?

(如何将上下文传递到setTimeout ?)

I want to call this.tip.destroy() if this.options.destroyOnHide after 1000 ms.

(如果this.options.destroyOnHide在1000毫秒后使用this.options.destroyOnHide ,我想调用this.tip.destroy() 。)

How can I do that?

(我怎样才能做到这一点?)

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

When I try the above, this refers to the window.

(当我尝试以上内容时, this是指窗口。)

  ask by JamesBrownIsDead translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

(也可以看看:)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...