我的对象有一个我想要恢复调用的函数.我的问题是如何使用setTimeout指向该对象实例的方法?
MyObject.prototype.Play = function() {
// do some stuff
setTimeout(thecurrentmethodnameHERE, 1000);
}
var test = new MyObject();
test.Play();
Run Code Online (Sandbox Code Playgroud)
只是这样做setTimeout(this.someMethod, 1000),但请记住,它将在全局上下文中调用,因此对this内部的任何引用都someMethod将是window假设Web浏览器.
你可以在构造函数中这样做,如果这是一个问题:
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);
};
Run Code Online (Sandbox Code Playgroud)
有些库定义Function.prototype.bind了你可以在这些情况下使用setTimeout(this.someMethod.bind(this), 1000)哪些,它只返回一个call()用你想要的对象编辑的新函数this,它是一个很好的,简单的函数,你可以实现而不会弄乱Function原型.