Implementing setTimeout()
inside a class function in JavaScript is my current goal. The purpose of setTimeout()
is to trigger another method within the same Class, so I have written the function as
window.setTimeout("this.anotherMethod", 4000)
. However, there lies the issue: this
references the calling Object, which in the case of setTimeout()
, is window
. How can enclosures be utilized to provide 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();
}
}
}