从静态方法ES6调用私有方法

时间:2018-10-23 10:36:51

标签: javascript jquery oop

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

spin_unlock*

我试图只公开内部调用所有私有方法的staticfun方法,但这给了我class a { fun1(){ console.log('fun1'); } static staticfun(){ console.log('staticfun'); this.fun1(); } } a.staticfun(); 不是一个函数。我试图找到许多方法来用“ this”找到它,但是它确实起作用。

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

3 个答案:

答案 0 :(得分:2)

fun1不是静态函数,因此您需要定义a类的新实例才能调用它:

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

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

a.staticfun();

您应该注意,这不是一个好习惯。您不应该拥有依赖于非静态逻辑的静态方法。

一种解决方法是将a的实例传递给静态函数,但这完全不符合使用静态方法的要点。

答案 1 :(得分:1)

首先,请阅读此SO question

有可能,您可以创建类a的实例,然后从该实例调用方法fun1

尽管,从静态方法中调用非静态方法是没有意义的。

static表示此方法属于对象(而不是实例)

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

a.staticfun();

答案 2 :(得分:0)

如果不想避免实例化函数,另一种方法是直接从类原型中调用函数(实际上是prototype属性,而不是__proto__)。

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

a.staticfun();
相关问题