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/

0

3 Answers 3

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0
function move (a) {
    setTimeout(
        function() { 
           if (a < 10) {
            a = a+ 1; 
            move(a);
           } 
        }, 500); }

move(0);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.