Context:
I have some class which at some point produces instances of itself, and it works fine. But now I would like to extend that class and realize that I would get an instance of a parent class.
Example:
class Line {
constructor(protected length: number) {}
divide(into: number): Line[] {
const size: number = Math.ceil(this.length / into);
return (new Array(into)).map(() => new Line(size));
}
}
class BoldLine extends Line {
constructor(protected length: number, private width: number) {
super(length);
}
getWidth() {
return this.width;
}
}
const line: BoldLine = new BoldLine(10, 2);
line.divide(2); // <== I'll get Line[] but would like to have BoldLine[];
Question:
How can I always get the instance of this.constructor class, even after inheritance?
And how can I do this in a seamless way, w/o passing constructor name as a parameter for divide method?
Thanks.