ES5 的类和 ES6 的 class 有什么区别?
参考答案
- 本质:class 是原型继承的语法糖,但不能像函数那样直接调用(必须 new,否则 TypeError);
- 严格模式:class 内部自动严格;
- 方法不可枚举:class 原型方法
enumerable: false;ES5 手工赋值为可枚举; - 无提升:class 声明存在 TDZ,不能先用后定义;函数声明可提升;
- 继承:class 用
extends+super,且super必须在访问 this 前调用;ES5 需寄生组合继承手工实现; - super 与 static:class 支持静态方法、getter/setter、计算属性名、
new.target; - 继承内置类:class 可正确继承 Array/Error 等(ES5 无法);
- this 绑定:class 方法默认严格,脱离实例调用 this 为 undefined(可加 autobind 或用箭头函数字段)。