tags:

views:

189

answers:

1

my object has a function that i want to call recurseively. my problem is how do i use setTimeout to point to the method of that instance of the object?

MyObject.prototype.Play = function() {

  // do some stuff
  setTimeout(thecurrentmethodnameHERE, 1000);
}

var test = new MyObject();

test.Play();
+3  A: 

Just do setTimeout(this.someMethod, 1000), but keep in mind that it will be called in a global context, so any reference to this inside someMethod will be window, assuming a web browser.

You can do it like this in your constructor, if that's an issue:

YourObject = function(name) {
  var self = this;
  self.name = name;
  self.someMethod = function() {
    alert(self.name); // this.name would have been window.name
  };
  setTimeout(self.someMethod, 1000);
};

Some libraries define Function.prototype.bind which you can use in these situations, setTimeout(this.someMethod.bind(this), 1000), which simply returns a new function that gets call()ed with your desired object as this, it's a nice, simple function that you can implement without messing with the Function prototype too.

nlogax
freakin nlogax, what are you doin here!
meder