简体   繁体   English

是否可以从类的静态方法中调用实例方法?

[英]Is it possible to call an instance method from a static method of a class?

It's easy to build instance methods that call on the polymorphic static method: 构建调用多态静态方法的实例方法很容易:

class MyClass {
  instanceMethod() {
    this.constructor.staticMethod();
  }
  static staticMethod() {
    console.log('first');
  }
}

class OtherClass extends MyClass {
  static staticMethod() {
    console.log('second');
  }
}
const i = new OtherClass();
i.instanceMethod();

However, I want to do the opposite - define a static method that calls upon the polymorphic instance method - sending this as a parameter. 但是,我想做相反的事情-定义一个调用多态实例方法的静态方法-将this作为参数发送。

class MyClass {
  instanceMethod() {
    console.log('first');
    this.constructor.staticMethod();
  }
  static staticMethod(self) {
     // how to call??
     instancefromstatic(this).instanceMethod.call(self);
  }
}

class OtherClass extends MyClass {
  instanceMethod() {
    console.log('second');
  }
}
OtherClass.staticMethod({});

If I understand you are after… 如果我了解您在追求……

When you call OtherClass.staticMethod() , this will be the OtherClass . 当你调用OtherClass.staticMethod() this将是OtherClass So if you want to access the instance method, you will find it on the this.prototype . 因此,如果要访问实例方法,可以在this.prototype上找到它。

 class MyClass { instanceMethod() { console.log('first'); this.constructor.staticMethod(); } static staticMethod(self) { this.prototype.instanceMethod() return this.prototype.testVal } } class OtherClass extends MyClass { instanceMethod() { console.log('second'); } get testVal(){ console.log("getting") return "test value" } } // logs 'second': console.log(OtherClass.staticMethod({})); 

Be careful in the MyClass instanceMethod , because you can create an infinite loop the way you have it setup if you call MyClass.staticMethod() MyClass instanceMethod要小心,因为如果调用MyClass.staticMethod()则可以按照设置方式创建无限循环。

Instance is merely a context of a method call in this case. 在这种情况contextInstance只是方法调用的context You are almost getting there. 你快到了。 Passing in self to the staticMethod. self传递给staticMethod。 And then you can call it via class name. 然后可以通过类名调用它。

MyClass.instanceMethod.call(self)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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