问题描述
我试图在JavaScript中的类函数中使用 setTimeout()
。 setTimeout()
应该在同一个类中触发另一个方法,所以我传递的函数写为 window.setTimeout(this .anotherMethod,4000)
。这带来了问题: this
引用调用对象,在 setTimeout()
的情况下,它是窗口
。如何使用附件来返回类对象本身的引用?
myObject = function(){
this.move = function(){
alert(this +is running);
}
this.turn = function(){
alert(this +is turning);
}
this.wait = function(){
window.setTimeout(this.run,(1000 * randomNumber(1,5)));
}
this.run = function(){
switch(randomNumber(0,2)){
case 0:
this.move );
break;
case 1:
this.turn();
break;
case 2:
this.wait();
}
}
}
var that = this;
setTimeout(function(){
that.doStuff();
},4000);
您还可以以获得更简洁的代码(如@Raynos最初指出的) p>
setTimeout(this.doStuff.bind(this),4000);
bind
此编码模式(即捕获此
词法)。
I am trying to use setTimeout()
inside a class function in JavaScript. The setTimeout()
is supposed to trigger another method in the same Class, so the function I am passing it is written as window.setTimeout("this.anotherMethod", 4000)
. That bring the problem: this
references the calling Object, in the case of setTimeout()
it is window
. How can I use enclosures to return a reference to the Class Object itself?
myObject = function(){
this.move = function(){
alert(this + " is running");
}
this.turn = function(){
alert(this + " is turning");
}
this.wait = function(){
window.setTimeout("this.run" ,(1000 * randomNumber(1,5)));
}
this.run = function(){
switch(randomNumber(0,2)){
case 0:
this.move();
break;
case 1:
this.turn();
break;
case 2:
this.wait();
}
}
}
You can do this:
var that = this;
setTimeout(function () {
that.doStuff();
}, 4000);
You can also bind
for more succinct code (as originally pointed out by @Raynos):
setTimeout(this.doStuff.bind(this), 4000);
bind
is a standard library function for exactly this coding pattern (ie capturing this
lexically).
这篇关于setTimeout()在JavaScript类中使用“this”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!