开发者

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

开发者 https://www.devze.com 2023-04-01 21:02 出处:网络
I\'m getting un开发者_如何学Pythondefined function when I try to do the following (simplified for readability)

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

精彩评论

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

关注公众号