class 是语法糖,本质是构造函数+原型操作:constructor 定义实例初始化逻辑,方法挂载到 prototype(不可枚举),static 方法赋值给类本身;extends 建立静态继承(Student.__proto__ === Person)和实例继承(Student.prototype.__proto__ === Person.prototype)。

JavaScript 中 class 语法糖不是新机制,它直接映射到已有的原型链结构——编译器(或 JS 引擎)会把它自动转成构造函数 + prototype 操作的组合。你写的每一行 class 代码,背后都有明确对应的原型操作。
class 声明如何生成构造函数和 prototype
-
class Person { constructor(name) { this.name = name; } }
等价于:function Person(name) { this.name = name; } Person.prototype.constructor = Person; 类中定义的实例方法(如
sayHi())
→ 自动挂载到Person.prototype上,且enumerable: false(不可枚举)
→ 和手动写Person.prototype.sayHi = function() { ... }效果一致static方法(如static create())
→ 直接作为属性赋值给函数对象本身:Person.create = function() { ... }
→ 它不进入原型链,也不被实例继承new Person()的行为
→ 创建空对象 → 将其[[Prototype]]指向Person.prototype→ 执行constructor并绑定this
extends 继承怎么连接原型链
class Student extends Person 不是“复制父类”,而是建立两条关键链接:
Student.__proto__ === Person
→ 静态继承:子类可访问父类的static方法Student.prototype.__proto__ === Person.prototype
→ 实例继承:new Student()能调用Person.prototype上的方法
这等价于:
function Student(name, grade) {
Person.call(this, name); // super() 的本质
this.grade = grade;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;constructor 和 super() 的原型意义
-
constructor是唯一初始化入口,必须用new调用,否则报错 -
super()在子类constructor中:- 先触发
Person.call(this, ...),确保父类初始化逻辑执行 - 同时让
this正确绑定到当前实例(否则this为undefined)
- 先触发
-
super.method()则是沿[[Prototype]]向上查找,等价于Person.prototype.method.call(this)
如何验证 class 的原型映射
你可以随时用这些表达式确认:
立即学习“Java免费学习笔记(深入)”;
-
Person.prototype.isPrototypeOf(new Person())→true -
Object.getPrototypeOf(new Person()) === Person.prototype→true -
Person.prototype.__proto__ === Object.prototype→true -
Person.__proto__ === Function.prototype→true(因为 class 本质是函数)
不复杂但容易忽略


















