JavaScript中不存在真正的类,class只是语法糖,核心机制是每个对象内部的[[Prototype]]原型链指针,属性查找沿链向上进行直至null。
[[Prototype]] 链指针JavaScript 中没有“类”作为真实的数据结构,class 只是语法糖。真正起作用的是每个对象都隐式关联的一个原型对象,即内部属性 [[Prototype]](可通过 Object.getPrototypeOf(obj) 读取,或非标准但广泛支持的 obj.__proto__ 访问)。当访问一个对象上不存在的属性时,JS 引擎会沿着这条链向上查找,直到找到该属性或到达 null。
class 声明本质是函数 + 原型赋值的语法糖写一个 class,等价于定义构造函数并手动设置其 prototype 属性:
class Person {
constructor(name) {
this.name = name;
}
say() {
return `Hi, I'm ${this.name}`;
}
}
// 等价于:
function Person(name) {
this.name = name;
}
Person.prototype.say = function() {
return `Hi, I'm ${this.name}`;
};
关键点:
class Person 声明后,Person.prototype 自动成为所有实例的 [[Prototype]]
new Person() 创建的对象,其 [[Prototype]] 指向 Person.prototype
static create())挂载在 Person 函数本身上,不进原型链class 继承都靠 Object.setPrototypeOf() 或 extends
实现extends 不是复制,而是建立原型链连接:
class Animal { eat() { return 'eating'; } }
class Dog extends Animal { bark() { return 'woof'; } }
// 等价于:
function Animal() {}
Animal.prototype.eat = function() { return 'eating'; };
function Dog() {}
Object.setPrototypeOf(Dog.prototype, Animal.prototype);
Dog.prototype.bark = function() { return 'woof'; };
Object.setPrototypeOf(Dog, Animal); // 静态继承
常见误解:
class A extends B 并不会把 B.prototype 的属性“拷贝”到 A.prototype —— 它只是让 A.prototype.[[Prototype]] === B.prototype
B.prototype 会影响所有已创建的 A 实例(因为共享原型链)prototype,不能用作构造函数,也不参与原型链构建instanceof 和 isPrototypeOf()
instanceof 检查的是「构造函数的 prototype 是否在对象的原型链上」;而 isPrototypeOf() 直接检查某个对象是否为另一对象的原型:
const d = new Dog(); console.log(d instanceof Dog); // true console.log(d instanceof Animal); // true(因为 Dog.prototype.[[Prototype]] === Animal.prototype) console.log(Animal.prototype.isPrototypeOf(d)); // true console.log(Dog.prototype.isPrototypeOf(d)); // true console.log(Person.prototype.isPrototypeOf(d)); // false
容易踩的坑:
Object.create(null) 创建的对象没有原型,instanceof 对任何构造函数都返回 false
Array 构造函数不相等,[].constructor === window.parent.Array 为 false,但 Array.isArray([]) 仍为 true(它绕过原型链,用内部 [[Class]] 标签)class 语法带来的“类思维”惯性,常常掩盖了底层对象关系的真实走向。真正理解它,不是记住“每个函数都有 prototype”,而是看清“每个对象都有 [[Prototype]],且只有一条向上单向链”。