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);
}
精彩评论