JS的class是语法糖,本质仍是构造函数+原型链:class声明等价于带prototype方法的函数,实例化过程与ES5相同,继承、super、static等均基于原型链实现。

JS 的 class 不是真正的新机制,而是一层“包装纸”——它背后还是你 already 熟悉的构造函数 + 原型链,只是写起来更像 Java、Python 那样规整、好读。
class 本质就是一个函数
虽然你用 class Person { ... } 写,但 JS 引擎看到的其实等价于一个带特殊检查的函数:
-
typeof Person返回"function",不是"class" - 它的
constructor方法就是这个函数的主体 - 你写的实例方法(比如
sayHello())会自动挂到Person.prototype上 - 类名不能被当作普通函数调用:
Person()会报错,必须用new Person()—— 因为底层加了检查,防止this指向全局
new 一个 class 实例,发生了什么?
和 ES5 构造函数一模一样,只是过程被封装得更干净:
- 创建一个空对象
- 把这个对象的
[[Prototype]]指向Person.prototype - 以这个新对象为
this,执行constructor函数 - 如果 constructor 没返回对象,就默认返回这个新对象
它为什么叫“语法糖”,而不是新模型?
因为所有面向对象行为,都靠原型链驱动:
- 继承用
extends,底层仍是Object.setPrototypeOf(Child.prototype, Parent.prototype) - 调用父类方法用
super.xxx(),本质是手动绑定Parent.prototype.xxx.call(this, ...) - 静态方法
static就是直接挂在函数对象本身上(Person.xxx),跟Function.xxx一个道理 - 私有字段
#age是新增的底层能力(ES2022),但它不改变原型链逻辑,只是加了一层访问控制
对比一下你就秒懂
这段 class:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + ' 叫了一声');
}
}
等价于这段 ES5 函数写法:
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(this.name + ' 叫了一声');
};
差别只在组织形式:class 把构造逻辑和方法声明收拢在一个块里,不散落各处,也不用反复写 .prototype。


















