javascript多级继承通过连续设置prototype实现,如parent→student→graduatestudent,需用object.create()构建原型链并修复constructor,避免new父类导致引用属性共享或参数错误。

JavaScript 中原型链本身不支持“多层级继承”的语法结构,但可以通过连续设置原型对象,自然形成多层原型链,从而实现多级继承效果。关键不在“多层”本身,而在于每一步都正确维护 __proto__ 链路和 constructor 指向。
多层级原型链的构建逻辑
原型链本质是一条从实例出发、逐级向上查找属性的路径:实例 → 子类原型 → 父类原型 → 更上层原型(如 Object.prototype)→ null。只要让每一级子类的 prototype 正确指向其直接父类的一个实例(或用 Object.create 创建干净代理),链路就自动延伸。
- 子类 A 继承父类 Parent:A.prototype = Object.create(Parent.prototype)
- 子类 B 再继承 A:B.prototype = Object.create(A.prototype)
- 此时实例 b 的原型链为:
b → B.prototype → A.prototype → Parent.prototype → Object.prototype → null
正确实现三(或更多)级继承的步骤
以 Parent → Student → GraduateStudent 为例,需确保每层都完成两件事:原型链连接 + constructor 修复。
- 用
Object.create(父类.prototype)设置子类原型,避免调用父类构造函数造成副作用 - 显式赋值
子类.prototype.constructor = 子类,否则 constructor 会指向父类 - 若需在子类构造中初始化父类自有属性(如 name、age),仍需在子类构造函数内用
Parent.call(this, ...)或Student.call(this, ...)
例如:
function Parent(name) { this.name = name; }Parent.prototype.say = function() { return `I'm ${this.name}`; };
function Student(name, grade) {
Parent.call(this, name); // 继承自有属性
this.grade = grade;
}
Student.prototype = Object.create(Parent.prototype);
Student.prototype.constructor = Student;
function GraduateStudent(name, grade, thesis) {
Student.call(this, name, grade); // 向上继承 Student 自有属性
this.thesis = thesis;
}
GraduateStudent.prototype = Object.create(Student.prototype);
GraduateStudent.prototype.constructor = GraduateStudent;
为什么不能直接 new 上级构造函数?
像 Student.prototype = new Parent() 这种写法,在两级继承时可能凑合,但到三级就暴露问题:
- new Parent() 会执行 Parent 构造函数,可能产生无意义的默认值(比如
this.colors = ['red']),这些引用类型会被所有 Student 实例共享 - GraduateStudent.prototype = new Student() 会再次触发 Student 构造函数,而此时无法传入合法参数,容易出错或污染原型
- 这种写法让原型对象携带了不应属于“原型”的实例状态,违背原型设计本意
ES6 class 的多层继承是同一套机制
class GraduateStudent extends Student 底层仍是通过 Object.setPrototypeOf(GraduateStudent.prototype, Student.prototype) 和 Object.setPrototypeOf(GraduateStudent, Student) 实现。它自动处理了 constructor 修复和 super 调用,但原型链层级关系完全一致:实例 → GraduateStudent.prototype → Student.prototype → Parent.prototype → Object.prototype → null。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











