I have next classes:
class Type {
static fromObject(obj = {}) {
return <new descendant object>
}
}
class CustomType1 extends Type {
constructor(a, b) {
this.a = a;
this.b = b;
}
}
class CustomType2 extends Type {
constructor(c, d) {
this.c = c;
this.d = d;
}
}
const t1 = CustomType1.fromObject({a:1, b:2})
const t2 = CustomType2.fromObject({c:3, d:4})
Expected result: t1 is instance of CustomType1 and t2 is instance of CustomType2
Question: It's possible to access child's class or prototype or constructor from parent class through static context in order to use method as factory.
new.targetto get access to the constructor: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…CustomType1.fromObjectthethisinfromObjectrefers toCustomType1, and forCustomType2.fromObjectthethisrefers toCustomType2, isn't that enough in your case?return new this(). The trickier part is to deconstruct the object into positional arguments…