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

JS OOP:如何在父类静态方法中访问子类构造函数实现工厂模式

问题解答

当然可以做到!这其实是JavaScript类继承中静态方法的一个常用特性——当子类调用继承自父类的静态方法时,方法内部的this会指向调用该方法的子类构造函数本身,正好能用来实现你需要的工厂方法功能。

实现方案

我们只需要修改父类Type的fromObject方法,利用this指向子类构造函数的特性来创建实例:

class Type { 
  static fromObject(obj = {}) { 
    // this 指向调用该方法的子类构造函数(比如CustomType1、CustomType2)
    const instance = new this();
    // 将传入对象的属性赋值给新实例
    Object.assign(instance, obj);
    return instance;
  } 
}

class CustomType1 extends Type { 
  constructor(a, b) { 
    super(); // 子类构造函数必须先调用super(),因为继承了Type
    this.a = a; 
    this.b = b; 
  } 
}

class CustomType2 extends Type { 
  constructor(c, d) { 
    super();
    this.c = c; 
    this.d = d; 
  } 
}

// 测试结果
const t1 = CustomType1.fromObject({a:1, b:2});
console.log(t1 instanceof CustomType1); // 输出 true
const t2 = CustomType2.fromObject({c:3, d:4});
console.log(t2 instanceof CustomType2); // 输出 true

细节说明

  1. 静态方法中的this指向:当你调用CustomType1.fromObject()时,静态方法内部的this就是CustomType1这个构造函数本身,所以new this()会直接创建CustomType1的实例。
  2. 子类构造函数的super()调用:因为CustomType1继承了Type,在子类构造函数中必须先调用super()才能使用this,否则会报错。
  3. 适配子类构造逻辑:如果你的子类需要严格按照构造函数的参数来创建实例(而不是直接赋值属性),可以让子类重写fromObject方法:
    class CustomType1 extends Type { 
      constructor(a, b) { 
        super();
        this.a = a; 
        this.b = b; 
      }
    
      // 重写fromObject,按构造函数参数创建实例
      static fromObject(obj = {}) {
        return new this(obj.a, obj.b);
      }
    }
    

额外说明

除了通过this访问子类构造函数,你还可以通过this.prototype访问子类的原型对象,比如用来检查原型上的方法或属性,但在这个工厂方法场景中,直接使用this创建实例就足够了。

内容的提问来源于stack exchange,提问作者dorintufar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:07:46