setTimeout的JavaScript对象方法名称

时间:2009-11-02 20:40:14

标签: javascript

我的对象有一个我想要连续调用的函数。 我的问题是如何使用setTimeout指向该对象实例的方法?

MyObject.prototype.Play = function() {

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

var test = new MyObject();

test.Play();

2 个答案:

答案 0 :(得分:7)

只需执行setTimeout(this.someMethod, 1000),但请记住,它将在全局上下文中调用,因此对thissomeMethod的任何引用都将为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);
}