Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
12
rated 0 times [  15] [ 3]  / answers: 1 / hits: 45037  / 13 Years ago, fri, may 6, 2011, 12:00:00

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();
}
}


}


More From » oop

 Answers
59

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).


[#92371] Thursday, May 5, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marisela

Total Points: 103
Total Questions: 105
Total Answers: 102

Location: Solomon Islands
Member since Fri, Oct 8, 2021
3 Years ago
;