es6 的 class 是对原型链继承的语法封装,使继承更清晰直观;它自动处理 prototype 操作、支持 extends 单继承、super 统一调用父类,并有 constructor 必须调用 super 等硬性约束。

ES6 的 class 不是全新机制,而是对原型链继承的语法封装——它让继承逻辑更清晰、写法更直观,不用手动操作 prototype 或 __proto__,也不用反复调用 Object.setPrototypeOf 或 Object.create。
用 class 声明基础类,自动绑定构造函数和原型方法
传统 ES5 中需分开定义构造函数和原型方法:
function Person(name) { this.name = name; }Person.prototype.sayHi = function() { console.log('Hi, ' + this.name); };
ES6 中直接写成一个结构块,语义集中:
class Person {
constructor(name) {
this.name = name;
}
sayHi() {
console.log('Hi, ' + this.name);
}
}
这样既避免了原型污染风险,也省去手动挂载方法的步骤,sayHi 默认不可枚举,更符合类的封装预期。
用 extends 实现单继承,自动建立原型链
子类只需声明 extends 父类,JavaScript 引擎会自动设置:
- 子类的
prototype继承父类的prototype - 子类的
constructor正确指向自身 - 静态方法、访问器(get/set)、实例属性全部继承
例如:
class Animal {
constructor(type) {
this.type = type;
}
move() { return `${this.type} is moving`; }
static breathe() { return 'All animals breathe'; }
}
class Dog extends Animal {
constructor(type, breed) {
super(type); // 必须调用,初始化父类 this
this.breed = breed;
}
bark() { return 'Woof!'; }
}
此时 Dog.prototype.__proto__ === Animal.prototype 成立,Dog.breathe() 也能直接调用。
super 关键字统一处理父类调用
super 在不同上下文有明确含义:
- 在子类
constructor中:代表父类构造函数,必须在使用this前调用 - 在实例方法中:代表父类的原型对象,可调用
super.method() - 在静态方法中:代表父类本身,支持
super.staticMethod()
比如重写 move 并增强逻辑:
class Dog extends Animal {
move() {
return super.move() + ' — and wagging tail';
}
}
这比 ES5 中手动写 Animal.prototype.move.call(this) 更安全、更易读。
注意几个关键约束,避免运行时错误
class 继承不是“无脑替换”,有几条硬性规则:
- 子类若定义了
constructor,必须第一行调用super(),否则this未初始化会报错 - 不能在调用
super()前访问this,哪怕只是console.log(this) - class 声明不会被提升(hoisting),必须先声明父类再
extends - class 内部方法默认是非构造函数、不可枚举、不可重写(除非显式用
Object.defineProperty修改)
这些限制看似严格,实则防止常见原型误操作,比如忘记绑定 this 或意外覆盖原型链。











