I have a function inside a object that sets up a interval that calls another function but when ever that interval function is called it gives my a error saying Uncaught TypeError: Object [object Window] has no method
here is my code that I’m trying to understand.
function test2() {
this.timer;
this.say = function(){
console.log("hi");
}
this.start = function() {
//starts the interval function
this.timer = setInterval(this.loop, 1000)
}
this.loop = function() {
//runs every 1 second
this.say(); //gives error -- Uncaught TypeError: Object [object Window] has no method 'say'
}
}
var test = new test2();
test.start();
Thank you for your help!
When
setInterval()fires, the context is the global context (e.g. window), not your object. To call a method on your object and have the value ofthisset appropriately in that method call, you need a separate function where you can call the method on your actual object like this:FYI, it is very common when using an asynchronous functions like timers or ajax to save the context
thisinto a local variable so it can then be referenced from the embedded callback function even whenthisis different in the callback function (as in your example). This is a common design pattern.