Kucl Stha
Kucl Stha

Reputation: 585

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

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 findOne(){
    // this has to return either an instance of Human
    // or an instance of Dog according to what calls it
    // How can I call new Human() or new Dog() here? 
  }
}

class Human extends Animal{
}

class Dog extends Animal{
}

const human = Human.findOne() //returns a Human instance
const day = Dog.findOne() //returns a Dog instance

Upvotes: 2

Views: 1909

Answers (1)

Bergi
Bergi

Reputation: 664620

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

Upvotes: 8

Related Questions