如何让父类modify方法调用时返回对应子类的实例?
让父类实例方法返回对应子类实例的实现方案
当然可以修改父类的modify方法,不用在子类里重写就能实现需求——核心是利用实例的constructor属性动态获取当前实例所属的类,替代硬编码的Parent。
修改后的代码
const modify = (data) => { const newData = { ...data }; // 示例:避免直接修改原数据,可根据实际逻辑调整 // 这里编写newData的具体修改逻辑 return newData; }; class Parent { constructor(data) { this.data = data; } modify() { // 用this.constructor替代硬编码的Parent return new this.constructor(modify(this.data)); } } class Child extends Parent { constructor(data) { super(data); } }
原理说明
在实例方法中,this.constructor指向当前实例所属的构造函数:
- 父类
Parent的实例调用modify时,this.constructor就是Parent,返回Parent实例 - 子类
Child的实例调用modify时,this.constructor就是Child,返回Child实例
这和静态方法里用new this()的逻辑完全等价,不需要在每个子类中重复重写modify方法,就能实现动态返回对应类实例的效果。
内容的提问来源于stack exchange,提问作者Sepehr Nazari
相关产品推荐
相关产品推荐

