es6 class继承有物理内核支撑:object.getprototypeof揭示原型链关系(子类构造函数、prototype及实例的[[prototype]]指向),reflect.construct实现new的底层逻辑并控制实例原型,二者协同还原super()执行路径。

ES6 Class 的继承不是语法糖,而是有明确的物理内核支撑:它依赖原型链([[Prototype]])和构造逻辑的精确控制。真正理解 Object.getPrototypeOf 和 Reflect.construct,就能看清 class 继承背后“谁是谁的原型”“实例如何被构造”这两个核心机制。
Object.getPrototypeOf 揭示 class 继承的原型链真相
Object.getPrototypeOf 返回对象内部 [[Prototype]] 指向的原型对象。在 class 继承中,它能清晰暴露三类关键关系:
-
子类构造函数的 prototype 指向父类实例原型:即
SubClass.prototype的[[Prototype]]是SuperClass.prototype -
子类构造函数自身继承父类静态方法:即
Object.getPrototypeOf(SubClass)===SuperClass(不是SuperClass.prototype) -
实例的原型链终点是 Object.prototype:每个实例最终通过
__proto__链向上追溯到Object.prototype
例如:
class A {}
class B extends A {}
console.log(Object.getPrototypeOf(B) === A); // true → B 继承 A 的静态属性
console.log(Object.getPrototypeOf(B.prototype) === A.prototype); // true → B.prototype 继承 A.prototype
const b = new B();
console.log(Object.getPrototypeOf(b) === B.prototype); // true
console.log(Object.getPrototypeOf(Object.getPrototypeOf(b)) === A.prototype); // true
Reflect.construct 是 new 操作符的底层等价实现
Reflect.construct(target, args, [newTarget]) 精确模拟了 new 的行为:创建空对象 → 设置其 [[Prototype]] → 用该对象作为 this 调用构造函数。它比 new 更透明,尤其在继承场景中暴露了“谁决定实例的原型”这一细节。
- 第三个参数
newTarget决定了新对象的[[Prototype]]—— 即newTarget.prototype会被设为实例的原型 - 如果不传
newTarget,默认使用target;但显式传入可绕过 class 的默认行为,实现更细粒度控制 - 它是 super() 在子类 constructor 中实际调用的底层机制
对比示例:
class A { constructor(x) { this.x = x; } }
class B extends A { constructor(x, y) { super(x); this.y = y; } }
// 等价于 new B(1, 2)
const b1 = Reflect.construct(B, [1, 2]);
// 强制让实例的原型指向 A.prototype(跳过 B.prototype)
const b2 = Reflect.construct(B, [1, 2], A);
console.log(Object.getPrototypeOf(b2) === A.prototype); // true
console.log(b2 instanceof B); // false(因为原型不是 B.prototype)
console.log(b2 instanceof A); // true
二者协同:还原 super() 的真实执行路径
当子类 constructor 中写 super(...args),引擎实际做了两件事:
- 调用
Reflect.construct,以new.target(即当前 new 调用的目标构造函数)为newTarget,确保新对象原型正确指向子类prototype - 再将该对象作为
this绑定,调用父类构造函数,完成初始化
也就是说:super() 不是简单调用父类函数,而是一次带原型指定的构造过程。若手动模拟,必须用 Reflect.construct 而非 call/apply,否则无法设置正确的 [[Prototype]]。
错误示范(丢失原型):
class B extends A {
constructor(x, y) {
// ❌ 错误:仅调用父构造函数,不创建带正确原型的对象
A.call(this, x); // this 是空对象,原型仍是 Object.prototype
this.y = y;
}
}
正确还原(需配合 Reflect.construct):
class B extends A {
constructor(x, y) {
const instance = Reflect.construct(A, [x], new.target);
instance.y = y;
return instance;
}
}
实战价值:动态继承、代理构造、兼容旧引擎
掌握这两个 API,可在运行时灵活操控继承关系:
- 构建可插拔的 mixin 类:用
Object.getPrototypeOf动态检查已有原型链,再用Reflect.construct注入新行为 - 实现构造函数代理(如日志、权限校验):拦截
new并委托给Reflect.construct,同时保留完整原型链 - 在不支持 class 的环境中模拟继承:用
Object.setPrototypeOf+Reflect.construct手动搭建等效结构
它们不是炫技工具,而是 JavaScript 原型模型在 ES6 中的正式接口化表达 —— 理解它们,等于拿到了 class 继承的源代码级说明书。











