ES6的class本质是函数和原型链的语法糖,底层仍基于原型继承;它将class编译为带内部属性的函数,extends自动设置原型链与构造函数绑定,super()确保父类初始化this,super.xxx访问父类原型方法。
ES6 的 class 本质是函数和原型链的语法糖,它没有引入新的面向对象机制,底层仍基于 JavaScript 原有的原型继承(prototype-based inheritance)。理解这点,就能看清 extends 和 super 背后发生了什么。
class 声明会被编译为一个具有特殊内部属性的函数(不可被当作普通函数调用,若不通过 new 会报错)。例如:
ES6 写法:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
等价于 ES5 函数写法:
function Animal(name) {
if (!(this instanceof Animal)) throw new TypeError("Class constructor Animal cannot be invoked without 'new'");
this.name = name;
}
Animal.prototype.speak = function() {
console.log(`${this.name} makes a sound.`);
};
可见,class 只是更简洁、更严格的函数 + 原型赋值封装。
extends 并非创建新继承模型,而是自动完成三件事:
prototype.__proto__ 指向父类的 prototype(实现方法继承)__prot
o__ 指向父类(实现静态方法/属性继承)super() —— 这实际是执行父类构造函数,并将 this 绑定到当前实例例如:
class Dog extends Animal {
constructor(name, breed) {
super(name); // ← 必须!等价于 Animal.call(this, name)
this.breed = breed;
}
}
若不写 super(),JavaScript 会抛出 ReferenceError: Must call super constructor in derived class before accessing 'this'。因为子类的 this 需要由父类构造函数初始化(尤其是涉及私有字段或某些内置类时)。
在构造函数中,super() 是调用;在方法中,super.xxx 是访问父类原型上的属性或方法:
class Dog extends Animal {
speak() {
super.speak(); // ← 相当于 Animal.prototype.speak.call(this)
console.log(`${this.name} barks!`);
}
}
其底层逻辑仍是:从 this.__proto__.__proto__(即 Animal.prototype)上查找方法。Babel 编译时会把 super.speak() 转成类似 Animal.prototype.speak.call(this) 的形式。
ES6 class 没有改变 JavaScript 的继承本质,但做了几项重要约束:
new 调用类构造器(避免忘记 new 导致 this 指向错误)super() 前访问 this(防止未初始化就使用)constructor 属性,且不可枚举(更符合预期)Sub.__proto__ === Super)这些不是新机制,而是对原型继承的“加固”和“规范”,让开发者更难写出不符合 OOP 直觉的代码。