Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 call one method from another [duplicate]

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(){    
  }  
}
like image 870
anivas Avatar asked Jan 27 '16 13:01

anivas


2 Answers

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

like image 80
anolsi Avatar answered Oct 24 '22 17:10

anolsi


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.

like image 44
Jai Avatar answered Oct 24 '22 18:10

Jai