我的对象有一个我想要连续调用的函数。 我的问题是如何使用setTimeout指向该对象实例的方法?
MyObject.prototype.Play = function() {
// do some stuff
setTimeout(thecurrentmethodnameHERE, 1000);
}
var test = new MyObject();
test.Play();
答案 0 :(得分:7)
只需执行setTimeout(this.someMethod, 1000)
,但请记住,它将在全局上下文中调用,因此对this
内someMethod
的任何引用都将为window
,假设网络浏览器。
如果这是一个问题,你可以在构造函数中这样做:
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);
};
某些库定义了Function.prototype.bind
,您可以在这些情况下使用setTimeout(this.someMethod.bind(this), 1000)
,它只返回一个新函数,该函数将call()
与您想要的对象this
进行对比,这是一个很好的,简单的功能,你可以实现而不会弄乱Function
原型。
答案 1 :(得分:0)
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);
}