ES6静态方法调用私有方法

Tap*_*ave 4 javascript oop jquery

我无法从类中的静态方法调用私有或非静态方法,下面是示例

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

a.staticfun();
Run Code Online (Sandbox Code Playgroud)

我试图仅公开 staticfun 方法,该方法在内部调用所有私有方法,但这给我的this.fun1不是一个函数。我试图找到很多方法来用“this”找到它,但它确实有效。

如何在静态方法中调用私有实例方法?

Sza*_*zab 5

另一种方法是直接从类原型(字面意思是属性prototype,而不是__proto__)调用该函数,如果您想避免实例化它。

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

a.staticfun();
Run Code Online (Sandbox Code Playgroud)