← 中文资源

简体中文版本

Reflect.construct 借用构造器

用不同的 newTarget 调用构造器,借用父类初始化逻辑,同时产出子类原型的实例。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

prototype is Point3D: true
describe: (1, 2) z=undefined
z is undefined: true
plain: (3, 4) | instance of Point3D: false

实现说明

活动部件是类 Point、Point3D。 plain 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 演示输出是带标签的(prototype is Point3D:、describe:、z is undefined:),每个操作都会留下自己的一行标注。

常见问题

不安装任何包也能运行吗?

可以,开箱即跑——没有引用任何内建 API 之外的东西。 状态都挂在模块顶层:plain。

核心语句

return '(' + this.x + ', ' + this.y + ')';
return super.describe() + ' z=' + this.z;

代码示例

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  describe() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}

class Point3D extends Point {
  constructor(x, y, z) {
    super(x, y);
    this.z = z;
  }

  describe() {
    return super.describe() + ' z=' + this.z;
  }
}

// Reflect.construct(target, args, newTarget):借用构造器但换原型
const p = Reflect.construct(Point, [1, 2], Point3D);
console.log('prototype is Point3D:', Object.getPrototypeOf(p) === Point3D.prototype);
console.log('describe:', p.describe());
console.log('z is undefined:', p.z === undefined);

// 对照:普通 new 只产出 Point 实例
const plain = new Point(3, 4);
console.log('plain:', plain.describe(), '| instance of Point3D:', plain instanceof Point3D);