ES6 class是原型继承的语法糖,编译后为函数、prototype操作和显式call;extends转为Object.create、constructor修复和__proto__赋值;super()等价于Parent.call(this)。

ES6 的 class 不是新继承模型,而是原型继承的“包装纸”。真正看透它,关键不是读语法,而是打开 Babel 编译后的代码——那里没有 extends 和 super,只有函数、prototype、Object.create 和显式的 call。
看编译结果里的构造函数本体
写一个最简 class Person { constructor(name) { this.name = name; } },Babel 会转成:
- 一个普通函数:
var Person = function Person(name) { _classCallCheck(this, Person); this.name = name; }; - 自动插入
_classCallCheck检查:确保必须用new调用,否则报错“Cannot call a class as a function” - 实例属性直接赋给
this,和手写构造函数完全一致
盯紧 prototype 上的方法挂载
类中定义的实例方法(如 sayHello())不会出现在函数体内,而是被收集起来,通过 _defineProperties 批量挂到 Person.prototype 上:
- 编译后能看到类似:
_defineProperties(Person.prototype, [{ key: "sayHello", value: function sayHello() { ... } }]); - 这意味着
sayHello是共享在原型上的,不是每个实例重复创建 - 它和 ES5 手写
Person.prototype.sayHello = function() {...}效果一模一样
拆解 extends 的三步原型链操作
class Child extends Parent 在编译后消失不见,取而代之的是清晰的三行原型操作:
-
Child.prototype = Object.create(Parent.prototype);—— 让子类原型继承父类原型方法 -
Child.prototype.constructor = Child;—— 修复构造器引用,避免new Child()实例的constructor指向Parent -
Child.__proto__ = Parent;—— 建立静态方法继承链,使Child.staticMethod()能访问Parent.staticMethod()
理解 super() 就是 Parent.call(this)
子类构造函数中 super(name) 不是魔法,编译后就是明确的父类调用:
- 等价于:
Parent.call(this, name); - 它负责初始化
this上的父类实例属性(比如this.name) - 不调就访问
this会报错,因为子类的this必须由父构造函数“激活”一次 - 在普通方法里写
super.xxx(),实际是Parent.prototype.xxx.call(this)
原型链没变,instanceof 依然可靠:一个 new Child() 对象,其 __proto__ 链仍是 Child.prototype → Parent.prototype → Object.prototype。所有继承行为,都落在 JavaScript 原生的原型机制之上。

















