JavaScript object method name for setTimeout
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 tha开发者_StackOverflowt instance of the object?
MyObject.prototype.Play = function() {
// do some stuff
setTimeout(thecurrentmethodnameHERE, 1000);
}
var test = new MyObject();
test.Play();
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.
Function.prototype.bind = function(scope) {
var _function = this;
return function() {
return _function.apply(scope, arguments);
}
}
MyObject.prototype.Play = function() {
// do some stuff
setTimeout(thecurrentmethodnameHERE.bind(this), 1000);
}
精彩评论