0

What is the correct way to reference an object function from within itself, so that I can call it several times using setTimeout in Javascript? In other words I want to be able to do this:

Foo.prototype.move = function() {
  if (this.count_a < 5) {
    this.count_a += 1;
    // setTimeout(this.move, 500);                    // doesn't work
    // setTimeout(function() { this.move(); }, 500);  // doesn't work
  }
}

I have tried a couple of things, none of which seem to work: http://jsfiddle.net/tga8r/1/

andersonvom
  • 11,701
  • 4
  • 35
  • 40

3 Answers3

1

The this property within the timeout will point to the object, that does execute the passed callback.

use .bind(this) to say, that the invoker have to use the this point to the passed object.

Foo.prototype.move = function() {
  if (this.count_a < 5) {
    this.count_a += 1;
    // setTimeout(this.move, 500);                    
    setTimeout(function() { this.move(); }.bind(this), 500);  
  }
}

or use a reference:

Foo.prototype.move = function() {
  var self = this;
  if (this.count_a < 5) {
    this.count_a += 1;
    // setTimeout(this.move, 500);                    
    setTimeout(function() { self.move(); }, 500);  
  }
}
Konstantin Krass
  • 8,626
  • 1
  • 18
  • 24
1

this has a global scope when the window timer function runs- it is out of your function and in the window.

label the this-

Foo.prototype.move= function(){
    var T= this;
    if(T.count_a<5){
        T.count_a += 1;
        setTimeout(function(){T.move();},500);
    }
}
kennebec
  • 102,654
  • 32
  • 106
  • 127
0
function move (a) {
    setTimeout(
        function() { 
           if (a < 10) {
            a = a+ 1; 
            move(a);
           } 
        }, 500); }

move(0);
Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Pratik
  • 1,550
  • 1
  • 9
  • 9