简体   繁体   中英

Invoking private method from static method ES6

I am unable to call private or non static method from static method in class, below is the example

class a {
 fun1(){
  console.log('fun1');
 }
 static staticfun(){
  console.log('staticfun');
  this.fun1();
 }
}

a.staticfun();

I am trying to expose only staticfun method which internally calls all private methods, but this gives me this.fun1 is not a function. I tried to find many ways to find it with 'this', but it does work.

How do I call private instance methods inside static methods?

fun1 is not a static function, so you need to define a new instance of the a class in order to call it:

 class a { fun1() { console.log('fun1'); } static staticfun() { console.log('staticfun'); new this().fun1(); } } a.staticfun(); 

You should note that this is not good practice, though. You shouldn't have a static method relying on non-static logic.

A workaround would be to pass an instance of a to the static function, but that completely defies the point of having a static method in the first place.

First, read this SO question

It's possible, You can create an instance of class a and then invoke from the instance the method fun1 .

Although, There is no sense to call a non-static method from a static one.

static means that this method belong to the object (not to the instance)

 class a { fun1(){ console.log('fun1'); } static staticfun(){ console.log('staticfun'); const classInstance = new a() classInstance.fun1(); } } a.staticfun(); 

Another way is to call the function directly from the class prototype (meaning literally the prototype property, not __proto__ ), if you want to avoid instantiating it.

class a {
 fun1(){
  console.log('fun1');
 }
 static staticfun(){
  console.log('staticfun');
  this.prototype.fun1();
 }
}

a.staticfun();

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