I code TypeScript with React.js. I have a parent class “EntityCollection” and a child class “ProductCollection”. I want to define a method for “EntityCollection” that create a new instance of the class. But in a child class it have to create an instance of the child class.
With PHP I would make something like this:
class Parent
{
public function hail(): void
{
print "hello, I'm " . static::class;
}
public function getNewObject(): static
{
return new static();
}
}
class Child extends Parent {}
$parent = new Parent();
$child = new Child();
$parent->getNewObject()->hail(); // hello, I'm Parent
$child->getNewObject()->hail(); // hello, I'm Child
The closest solution I’ve found is “eval” function:
export class EntityCollection {
makeNewClass() {
return new (eval(this.constructor.name))();
}
}
but the problem is the child class is in a separated file and I’ve got an error: “ReferenceError: ProductCollection is not defined”.
I’ve also tried Object.create(this);
– the problem here is we don’t have exactly the same structure, if I did new ProductCollection(), but I need it like it is in PHP with new static()
. I don’t like the idea to override the method in each child, it’s just ridiculous.