I have a JavaScript class
function MyClass() {
MyClass.prototype.fooMethod = function () {
// some logic goes here...
}
MyClass.prototype.fooMethod2 = function () {
this.fooMethod();
}
}
Everything works as expected when I call like this:
var m = MyClass();
m.fooMethod2();
However when I have this code called by setInterval I get an error: “Uncaught TypeError: Object [object DOMWindow] has no method ‘fooMethod'”
var m = MyClass();
var intervalId = setInterval(m.fooMethod2, 100);
Is there any way I can use setInverval to call my method?
In javascript, context (the value of
this) is set by how the method is invoked. Sofoo.bar()will setthistofooinside thebarfunction.But when you return a a reference to a function to be run by something else, context is not preserved. Check this out:
In this snippet, we pass a function into the
callLaterfunction. But when we invokefn()we do it without any receiver, meaning we lose context.So anytime function context is important, you have to pass in an anonymous function that will call the method on an object explicitly.