JavaScript的class是原型继承的语法糖,实例通过__proto__链访问构造函数的prototype;constructor初始化属性,普通方法挂载到prototype,static方法挂载到类自身。

JavaScript 的 class 语法只是原型继承的语法糖,它本身不改变底层机制——所有实例依然通过 __proto__ 链访问构造函数的 prototype 对象。
如何用 class 定义类(含构造器与方法)
定义一个类只需使用 class 关键字,内部用 constructor() 初始化实例属性,其他方法直接写函数名即可,**不需要逗号分隔**。
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, I'm ${this.name}`;
}
static describe() {
return "A human being";
}
}
-
constructor是唯一特殊方法,省略时会默认提供空构造器 - 普通方法(如
greet)自动添加到Person.prototype上 -
static方法挂在Person函数自身,不进入原型链 - 类声明不会被提升(
ReferenceError),必须先声明后使用
class 实例的原型链长什么样
创建实例后,其隐式原型指向类的 prototype,而类的 prototype 的 constructor 指回类本身;若存在继承,还会多一层 __proto__ 指向父类的 prototype。
const p = new Person("Alice", 30);
console.log(p.__proto__ === Person.prototype); // true
console.log(Person.prototype.constructor === Person); // true
console.log(p.__proto__.__proto__ === Object.prototype); // true
- 每个实例的
__proto__都是Person.prototype,不是Person -
Person.prototype默认只有constructor和你定义的方法,没有实例属性 - 不要直接修改
__proto__,应通过Object.setPrototypeOf()或extends控制继承关系
用 extends 实现继承时原型链如何连接
子类通过 extends 继承父类后,有两层原型连接:实例 → 子类 prototype → 父类 prototype → Object.prototype;同时子类函数的 __proto__ 指向父类函数,实现静态方法继承。
立即学习“Java免费学习笔记(深入)”;
class Student extends Person {
constructor(name, age, grade) {
super(name, age); // 必须调用,否则报错
this.grade = grade;
}
study() {
return `${this.name} is studying`;
}
}
-
Student.prototype.__proto__ === Person.prototype(方法继承的关键) -
Student.__proto__ === Person(所以能访问Person.describe()) -
super()必须在this使用前调用,否则报ReferenceError - 如果子类没写
constructor,会隐式添加constructor(...args) { super(...args); }
真正容易被忽略的是:即使写了 class,你仍然得理解 prototype、__proto__ 和 constructor 三者的关系——因为调试时看到的属性来源、instanceof 判断、甚至 Babel 编译后的代码,全依赖这套原型链。写 class 不等于脱离原型,只是换了一种更可控的组织方式。











