ES6 class本质是构造函数的语法封装,仍基于原型链继承;Babel将其编译为function与Object.setPrototypeOf逻辑;super()必须首行调用以绑定this原型链,不可省略。

ES6 class 本质仍是构造函数,不是新语法糖的替代品
很多人误以为 class 是 JavaScript 的“真正面向对象”起点,其实它只是对原型链继承的语法封装。Babel 编译后,class 会转成基于 function 和 Object.setPrototypeOf 的构造函数逻辑。这意味着:你没法绕过原型链理解继承。
选择 class 还是传统构造函数,关键看团队习惯、工具链支持和是否需要动态构造逻辑:
-
class更适合定义明确的、有层级关系的业务模型(如User、AdminUser),写法简洁,super()、static、get/set语义清晰 - 构造函数更适合需要运行时生成类、或与旧库深度集成的场景(比如封装 jQuery 插件工厂)
- 若需在继承中操作
new.target或做参数预处理,构造函数更直接;class中必须在constructor第一行调用super(),限制更多
用 extends 实现继承时,super() 必须显式调用且位置固定
这是最常见的报错源头:不调用 super() 会直接抛出 ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor。它不是可选步骤,而是语言强制要求。
super() 的作用不只是初始化父类实例属性,更重要的是为子类构造函数中的 this 绑定原型链——即把 this.__proto__ 指向 Parent.prototype。漏掉它,this 就是未初始化状态。
立即学习“Java免费学习笔记(深入)”;
class Parent {
constructor(name) {
this.name = name;
}
}
class Child extends Parent {
constructor(name, age) {
// ✅ 正确:必须在访问 this 前调用
super(name);
this.age = age;
}
}
注意:super() 不等于 Parent.call(this, ...)。前者还会设置内部属性 [[HomeObject]],影响 super.method() 的解析;后者只是普通函数调用,不会建立正确的原型委托链。
想复用构造函数逻辑但不走 extends?用 Object.setPrototypeOf() + call() 手动模拟
当你要让一个普通函数“假装继承”另一个函数(比如兼容老代码、或实现 mixin 式组合),不能只靠 call(),否则实例无法访问父类原型方法。必须手动补全原型链。
常见错误写法:
function Parent(name) {
this.name = name;
}
Parent.prototype.say = function() { return 'hi'; };
function Child(name, age) {
Parent.call(this, name); // ❌ 只复制了实例属性,没连原型
this.age = age;
}
const c = new Child('Alice', 10);
c.say(); // TypeError: c.say is not a function
正确做法:
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
// ✅ 补上原型链
Object.setPrototypeOf(Child.prototype, Parent.prototype);
const c = new Child('Alice', 10);
c.say(); // 'hi'
这个模式在封装第三方 SDK 适配层时很实用,但要注意:现代项目优先用 class + extends,手动操作原型易出错且难维护。
继承链过深或混用 class 与构造函数时,instanceof 和 isPrototypeOf() 表现可能不一致
instanceof 检查的是整个原型链上是否存在右侧构造函数的 prototype,而 isPrototypeOf() 直接检查某个对象是否在另一对象的原型链中。两者在混用 class 和函数构造器时可能给出不同结果,尤其涉及 Babel 转译或自定义 Symbol.hasInstance 时。
例如:
class A {}
function B() {}
Object.setPrototypeOf(B.prototype, A.prototype);
const b = new B();
console.log(b instanceof A); // true(正常)
console.log(A.prototype.isPrototypeOf(b)); // true
// 但如果 B 是通过 class 定义,再手动改 prototype:
class C {}
C.prototype = Object.create(A.prototype); // ❌ 破坏 class 内部 [[Prototype]] 关系
const c = new C();
console.log(c instanceof A); // false(即使原型链看起来一样)
根本原因是:class 构造函数的 prototype 属性不可写(严格模式下赋值静默失败),且引擎对 instanceof 的实现依赖内部标记。一旦破坏 class 的原始 prototype 对象,行为就不可靠。
所以,继承结构一旦选定(class 或函数),尽量保持统一;跨类型混用时,优先用 Object.getPrototypeOf() 逐级检查,比 instanceof 更可控。










