You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让父类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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 17:52:13