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();
}
}
}
Ran into a more complex situation...class A has a member of type B and a method that calls setTimeout which calls a method on class B. Solved as follows:
Which bound A.b to this within B.tick and worked.
Here's a fiddle with
bind
: https://jsfiddle.net/jrme9hyh/And one without
bind
which fails: https://jsfiddle.net/2jde8tq3/Have you tried;
Shorter way. Without anonymous func.
you can just use the arrow function syntax:
You can also bind a function to scope.
setTimeout(this.run.bind(this) ,(1000 * randomNumber(1,5)));
Be warned
Function.prototype.bind
is ES5inside
func
,this
always refer to the global object. you can pass in the current object into func,unfortunately it does NOT work in IE
Note that passing additional parameters to the function in the first syntax does not work in Internet Explorer.