ES6类继承是原型链的语法封装,转译后为ES5构造函数,instanceof可靠;super()首行调用父构造函数,extends设置原型链与constructor;实例方法挂prototype,静态方法挂构造函数。

ES6 类继承在运行时完全兼容 JavaScript 原有机制,不是新模型,而是对原型链的语法封装;转译(如 Babel)后还原为 ES5 风格的构造函数与原型操作,确保老环境可执行。
继承关系仍走原型链,instanceof 完全可靠
一个 class Child extends Parent 创建的实例,其原型链是:Child.prototype → Parent.prototype → Object.prototype
因此以下判断全部为真:
child instanceof Childchild instanceof Parentchild instanceof Object
这说明 class 继承没有改动底层对象模型,只是省去了手动设置 Child.prototype = Object.create(Parent.prototype) 等易错步骤。
转译后仍是构造函数,但加了 new 强制校验
Babel 将 class Person 编译为普通函数,并插入 _classCallCheck(this, Person) 检查:
- 若用
Person()直接调用,this不是Person实例,抛出"Cannot call a class as a function" - 若用
new Person(),this是新对象且this instanceof Person === true,检查通过
这种限制比 ES5 更严格,避免因遗漏 new 导致 this 指向错误。
extends 和 super 都对应明确的原型操作
extends 在转译中调用类似 _inherits(Child, Parent) 的辅助函数,完成三件事:
- 让
Child.prototype继承自Parent.prototype(即Object.create(Parent.prototype)) - 修复
Child.prototype.constructor指回Child - 设置
Child.__proto__指向Parent,使静态方法可被继承
super() 在子类构造器中必须首行调用,它实际执行的是父类构造函数,并把 this 绑定好,之后才能添加子类自己的属性。
方法和静态成员的挂载位置清晰可追溯
类中定义的内容按语义分层挂载:
- 实例属性(
this.xxx)和实例方法(箭头函数形式)→ 直接赋值给this - 普通方法(如
sayHello())→ 挂到Constructor.prototype上,由_defineProperties辅助函数处理 - 静态方法(带
static)→ 挂到构造函数本身(Constructor),不进原型链
这种分离方式与 ES5 手写模式完全一致,调试或 polyfill 时逻辑路径一目了然。


















