JS OOP:从父方法访问后代的构造函数



我有下一堂课:

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})

预期结果:t1 是 CustomType1 的实例,t2 是 CustomType2 的实例

问:可以通过静态上下文从父类访问子类或原型或构造函数,以便将方法用作工厂。

fromObject中的this将喜欢您调用的任何其他函数(执行上下文绑定的箭头函数除外(引用调用它的对象,因此在您的情况下,它将是CustomType1CustomType2CustomType1CustomType2是这些类的构造函数

class Type {
static fromObject(obj = {}) {
return new this(obj.a, obj.b)
}
}

最新更新