简体   繁体   中英

Call a static method inside other static method of a class in Javascript

I have a class with some static methods. I am trying to call one of my static methods inside another static method of the same class.

I have tried to call it with this.constructor.method(); and it doesn't work because the right this is not binded properly there.

I have also tried to bind the right this to the method were i want to call the other method. this.constructor.listenerFunc.bind(this.constructor) . Still not working.

Here is how the code looks like:

 class MyClass { constructor() { }; static firstMethod(){ //do some things this.constructor.secondMethod(); }; static secondMethod(){ //do other things }; } var x = new MyClass; console.log(x)

Apart from the typo, which prevents your example from working, you can use both the this. notation and a classical static call :

 class MyClass { constructor() { }; static firstMethod(){ this.secondMethod(); MyClass.secondMethod(); }; static secondMethod(){ console.log('I was called!'); }; } MyClass.firstMethod();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM