ES6 calls one method from another

I'm new to ES6 syntax, my source code has more implementation, but I simplified it. I get an error, I can not read the property "Method2" undefined. What am I doing wrong here? Do I need to make any binding calls.

class Class1 { constructor() { eventbus.subscribe(this.Method1); } Method1() { this.Method2(); } Method2(){ } } 
+5
source share
2 answers

You need to do eventbus.subscribe(this.Method1.bind(this));

Since you are linking the method to run elsewhere, you are sure to make sure in which area it will work. Forcing binding to this will ensure that an instance of Class1 is used.

EDIT: since ES6 allows you to perform the functions of arrows, you can also do eventbus.subscribe(() => this.Method1()); as it was reviewed by @torazaburo

+2
source

cannot read property "Method2" undefined

Most likely, you are not creating any object of the same class, or perhaps you are missing the new keyword to create a new object.

 var cls = Class1(); // will throw error. cls.Method1(); 

What did I mean if you do:

 var cls = new Class1(); cls.Method1(); // will get executed. 

demo version of es6fiddle.

+2
source

Source: https://habr.com/ru/post/1241616/


All Articles