JavaScript类继承:父类方法如何返回子类实例?
让JavaScript父类方法返回子类实例的实现方式
你遇到的问题是子类继承父类后,调用父类的方法会返回父类实例,而非子类实例。解决这个问题的关键是动态获取当前实例的构造函数,而非在父类方法里硬编码父类名称。
修改后的代码示例
class Vector { constructor(...c) { this.components = c; } add(c) { // 用this.constructor替代硬编码的Vector,动态获取当前类 return new this.constructor(this.components[0] + c); } } class Vec2 extends Vector {} // 测试效果 const myVec2 = new Vec2(5); const newVec2 = myVec2.add(3); console.log(newVec2 instanceof Vec2); // 输出 true console.log(newVec2.components); // 输出 [8]
原理说明
this.constructor会指向当前实例所属的类:
- 调用父类
Vector实例的add方法时,this.constructor就是Vector,返回Vector实例; - 调用子类
Vec2实例的add方法时,this.constructor就是Vec2,返回Vec2实例。
这种方式的好处是父类后续重构时,子类不需要做任何修改,就能保持方法返回自身实例的逻辑,完全匹配你想要的效果。
内容的提问来源于stack exchange,提问作者bronkula
相关产品推荐
相关产品推荐

