I am new to ES6 syntax, my original code has more implementation, but I have simplified. I am getting an error saying cannot read property 'Method2' of undefined. What am I doing wrong here ? Do I have to do any bind calls.
class Class1 {
constructor() {
eventbus.subscribe(this.Method1);
}
Method1() {
this.Method2();
}
Method2(){
}
}
You need to do eventbus.subscribe(this.Method1.bind(this));
Since you are associating the method to run on other place, you will be sure under which scope it will run. Forcing the bind to this will assure that is the instance of Class1
that will be used.
EDIT: Since ES6 allow arrow functions you can also do eventbus.subscribe(() => this.Method1());
, as it was refereed by @torazaburo
cannot read property 'Method2' of undefined
Most probably you are not creating any object of same class or may be you are missing the new
keyword to create new object.
var cls = Class1(); // will throw error.
cls.Method1();
What i meant if you do:
var cls = new Class1();
cls.Method1(); // will get executed.
es6fiddle demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With