How to create an instance of a subclass from the super class?

后端 未结 1 1503
名媛妹妹
名媛妹妹 2020-11-27 08:23

I am creating a class and its subclasses, where I am required to call a static method of the parent to return a child instance.

class Animal{
  static findOn         


        
相关标签:
1条回答
  • 2020-11-27 09:08

    The static method is called with its this value being the class object, the constructor of the subclass that you called it upon. So you can just instantiate that with new:

    class Animal {
      static findOne() {
        return new this;
      }
    }
    
    class Human extends Animal{
    }
    
    class Dog extends Animal{
    }
    
    const human = Human.findOne() // returns a Human instance
    const dog = Dog.findOne() // returns a Dog instance
    
    0 讨论(0)
提交回复
热议问题