开发者

Javascript - can't use object methods when called inside a function thats running through interval?

I'm getting un开发者_如何学Pythondefined function when I try to do the following (simplified for readability)

function object() {
  this.bar = function() { };

  this.foo = function() {
    this.bar();
  };

  this.z = setInterval(this.foo, 1000);

}

This code gives 'undefined function this.bar()' when executed from within the interval, but not when this.foo is called outside of the interval.

How can I achieve this?


That is correct - you can't do it that way. The this pointer will not be set correctly when called from setInterval() (it is probably set to point to the global window object). You can change your code like this to solve the problem:

function object() {
  this.bar = function() { };

  this.foo = function() {
    this.bar();
  };
  var self = this;   // save reference to local object in variable other than 'this'

  this.z = setInterval(function() {
    self.foo();      // call method on local object
  }, 1000);

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜