最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript object method name for setTimeout - Stack Overflow

programmeradmin1浏览0评论

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();

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();
Share Improve this question edited Nov 2, 2009 at 20:46 Will asked Nov 2, 2009 at 20:40 WillWill 1,6224 gold badges25 silver badges39 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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);
}
发布评论

评论列表(0)

  1. 暂无评论