0

I want to create an instance of child class from a static method in a base class

class Base {
  static find(id) {
    const attributes = database.get(id);
    return new getChildClass(attributes);
  }
}

class FirstChild extends Base {
}

class SecondChild extends Base {
}

I want FirstChild.find(1) to return an instance of FirstChild and SecondChild.find(1) to return an instance of SecondChild

Is in possible to achieve this in node JS?

Hirurg103
  • 4,783
  • 2
  • 34
  • 50

1 Answers1

2

When calling find from the child class, this inside find will refer to that child class, so you can just return new this from find:

class Base {
  static find(id) {
    const attributes = 'foo'; // database.get(id);
    return new this(attributes);
  }
}

class FirstChild extends Base {
}

class SecondChild extends Base {
}

console.log(FirstChild.find(1) instanceof FirstChild);
console.log(SecondChild.find(1) instanceof SecondChild);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320