原型链的本质是对象的__proto__指向其构造函数的prototype;所有继承均通过[[Prototype]]隐式链接实现,class是语法糖,super()必须调用以正确设置__proto__,Object.setPrototypeOf()比直接操作__proto__更安全。

原型链的本质是对象的 __proto__ 指向其构造函数的 prototype
JavaScript 中没有类继承的底层机制,所有“继承”都靠对象间隐式链接实现。每个对象都有一个内部属性 [[Prototype]](可通过 __proto__ 访问),它指向另一个对象——即该对象的原型。而这个原型对象,通常就是创建它的构造函数的 prototype 属性值。
例如:
function Person(name) {
this.name = name;
}
Person.prototype.say = function() { return 'Hi'; };
const p = new Person('Alice');
console.log(p.__proto__ === Person.prototype); // true
console.log(p.say()); // 'Hi'当访问 p.say 时,JS 引擎先查 p 自身属性,没找到就顺着 __proto__ 去 Person.prototype 查,再找不到会继续向上(比如 Person.prototype.__proto__ === Object.prototype),直到为 null ——这条链就是原型链。
用 class 语法实现继承必须配合 extends 和 super()
class 是语法糖,背后仍是原型链。但若想让子类正确继承父类实例属性和原型方法,extends 只是第一步,关键在子类构造函数中调用 super()。
-
super()必须在使用this前调用,否则报错ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor -
super()不仅初始化父类实例属性,还把子类实例的__proto__正确设为Parent.prototype - 若省略
super(),子类实例的__proto__会默认指向Function.prototype,导致继承链断裂
示例:
class Animal {
constructor(name) {
this.name = name;
}
speak() { return `${this.name} makes a sound`; }
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // ✅ 必须有
this.breed = breed;
}
bark() { return 'Woof!'; }
}
const d = new Dog('Buddy', 'Golden');
console.log(d.speak()); // 'Buddy makes a sound'
console.log(d.__proto__ === Dog.prototype); // true
console.log(Dog.prototype.__proto__ === Animal.prototype); // true
手动模拟继承时,Object.setPrototypeOf() 比直接赋值 __proto__ 更安全
不使用 class 时,有人会写 Child.prototype.__proto__ = Parent.prototype 来连接原型链。这种写法在部分环境(如旧版 Safari)可能失效或不可枚举,且 __proto__ 已被列为废弃属性。
推荐用标准 API:
function inherit(Child, Parent) {
Object.setPrototypeOf(Child.prototype, Parent.prototype);
// 或等价写法:Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child; // 修复 constructor 指向
}
-
Object.setPrototypeOf()是 ES6 标准方法,行为可预测 -
Object.create(Parent.prototype)创建新对象并设其[[Prototype]],但需额外修复constructor,否则new Child()实例的constructor会指向Parent - 不要用
Child.prototype = Parent.prototype—— 这会让父子共享同一原型对象,修改子类原型会影响父类
继承后实例的 instanceof 判断依赖原型链上是否存在对应 prototype
obj instanceof Constructor 的逻辑是:检查 obj.__proto__ 是否等于 Constructor.prototype,如果不等,就继续查 obj.__proto__.__proto__,直到匹配或到 null。
立即学习“Java免费学习笔记(深入)”;
这意味着:
- 如果手动改了
__proto__但没连通整条链(比如漏了Parent.prototype.__proto__),instanceof会返回false -
class A extends B后,new A() instanceof B为true,因为A.prototype.__proto__ === B.prototype - 箭头函数没有
prototype,不能用作构造函数,也无法被instanceof正确识别为“父类”
原型链越深,instanceof 查找越慢;生产环境慎用多层深度继承。











