简体   繁体   中英

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.

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 . So if you want to access the instance method, you will find it on the 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()

Instance is merely a context of a method call in this case. You are almost getting there. Passing in self to the staticMethod. And then you can call it via class name.

MyClass.instanceMethod.call(self)

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