This isn't my actual code (hopefully obviously), but it's a very short example that demonstrates the problem.
I'm writing a class with a method that accepts a callback as an argument. When the method finishes, it should call the callback.
class Demo {
constructor() {
this.method1();
}
method1() {
console.log("Method1");
this.method2(this.method1);
}
method2(onDone) {
console.log("Method2");
onDone();
}
}
new Demo();
So I want this to jump back and forth between calling method1
and method2
. If it worked properly, I should end up with a stack overflow, but instead what happens is this:
Method1
Method2
Method1
Uncaught TypeError: Cannot read property 'method2' of undefined
at method1 (demo.js:8)
at Demo.method2 (demo.js:13)
at Demo.method1 (demo.js:8)
at new Demo (demo.js:3)
Somehow, when we enter method1
the second time its been forgotten that this
is an instance of Demo
. I tried replacing onDone()
in method2
with this.onDone()
but then it completely fails to find onDone
(which makes sense - onDone
is the name of an argument, not the name of a member of Demo
.)
What is the proper way of doing this?