ES6 class 与 ES5 构造函数有什么区别?
class 是构造函数的语法糖,但有一些关键区别:
主要区别
| 特性 | ES5 构造函数 | ES6 class |
|---|---|---|
| 声明提升 | ✅ 有提升 | ❌ 无提升(TDZ) |
| 不加 new 调用 | 作为普通函数执行 | 报错 |
| 原型方法可枚举 | ✅ 可枚举 | ❌ 不可枚举 |
| 静态方法 | Foo.staticMethod = fn |
static method() |
| 私有字段 | 闭包模拟 | #field 语法 |
| 多继承 | 不支持 | 不支持(但可用 mixin) |
代码对比
// ES5
function Person(name) {
this.name = name
}
Person.prototype.sayHi = function () {}
Person.create = function () { return new Person('default') }
// ES6
class Person {
#age = 0 // 私有字段
constructor(name) {
this.name = name
}
sayHi() {} // 不可枚举
static create() {
return new Person('default')
}
get age() { return this.#age }
}class 的特殊行为
class声明存在暂时性死区,不能在声明前使用class内部默认使用严格模式class的方法定义在prototype上,且enumerable: false