我正在尝试setTimeout()
在 JavaScript 中的类函数中使用。本setTimeout()
应该引发在同一类的另一种方法,所以我向它传递函数写成window.setTimeout("this.anotherMethod", 4000)
。这带来了问题:this
引用调用对象,在setTimeout()
它的情况下是window
. 如何使用附件返回对类对象本身的引用?
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();
}
}
}