Ryan Tuosto
Ryan Tuosto

Reputation: 1951

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

I'm getting undefined 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?

Upvotes: 0

Views: 110

Answers (1)

jfriend00
jfriend00

Reputation: 707278

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

}

Upvotes: 2

Related Questions