说说 Class 语法糖的底层实现
参考答案
一句话
class 是构造函数的语法糖:本质仍是"函数 + 原型链",只是语法更清晰、并额外提供了继承、super、静态方法、私有字段等糖衣。编译到 ES5 后就是一个 IIFE + 原型赋值。
编译后的样子
// ES6
class Person {
constructor(name) { this.name = name; }
speak() { return this.name; }
static create(n) { return new Person(n); }
}
// 大致等价于
function Person(name) {
if (!(this instanceof Person)) throw new TypeError('Class constructor cannot be invoked without new');
this.name = name;
}
Person.prototype.speak = function () { return this.name; };
Object.defineProperty(Person.prototype, 'speak', { enumerable: false, writable: true, configurable: true });
Person.create = function (n) { return new Person(n); };
class 比函数"多"的行为
- **必须
new调用**:直接Person('a')会报TypeError(构造函数允许裸调)。 - 不能提升:class 声明存在 TDZ,声明前使用报
ReferenceError。 - 方法不可枚举:原型方法通过
Object.defineProperty定义,for...in不会遍历(函数写法是 enumerable)。 - 默认严格模式:class 体内代码自动严格模式。
- **
super**:提供对父类构造器/方法的访问,函数写法要手动Parent.call(this)+ 原型链。 - 静态继承:
class Child extends Parent时,Child.__proto__ === Parent,静态成员可继承。 - **
new.target**:可用于检测是否被new调用。 - **私有字段
#x**:真正的运行时私有(函数写法只能靠闭包/WeakMap)。
继承的本质
class Child extends Parent { constructor() { super(); } }
// 等价于: Child.prototype = Object.create(Parent.prototype); Child.prototype.constructor = Child;
// 且 Child.__proto__ = Parent(静态继承)
注意
"语法糖"不等于"完全等价":new 限制、不可枚举、TDZ、严格模式都是 class 独有的语义,说"完全一样"是不准确的。