javaScript继承有5种方式:1.原型链继承(共享引用属性);2.构造函数继承(私有属性但无原型方法);3.组合继承(功能全但父构造函数调用两次);4.寄生组合继承(只调用一次父构造,es6底层实现);5.class extends(语法糖,推荐日常使用)。

javascript 实现继承的核心是让子类能访问并复用父类的属性和方法,同时支持实例化和原型链的正确连接。ES6 之前主要靠手动模拟,ES6 引入 class 和 extends 后语法更简洁,但底层仍基于原型机制。目前主流有 5 种实用继承方式,各有适用场景。
1. 原型链继承
将父类的实例赋给子类的 prototype,子类实例通过原型链向上查找父类方法和共享属性。
优点:简单、复用父类方法;缺点:所有子类实例共享父类引用类型属性(如数组、对象),无法向父类构造函数传参。
function Parent() { this.colors = ['red', 'blue']; } Parent.prototype.sayHi = function() { console.log('Hi'); }; function Child() {} Child.prototype = new Parent(); // 关键:继承原型 Child.prototype.constructor = Child; // 修复 constructor const c1 = new Child(); c1.colors.push('green'); const c2 = new Child(); console.log(c2.colors); // ['red', 'blue', 'green'] ← 被意外修改
2. 构造函数继承(经典借用构造函数)
在子类构造函数中用 call 或 apply 调用父类构造函数,实现属性“私有化”继承。
立即学习“Java免费学习笔记(深入)”;
优点:避免引用类型共享,支持向父类传参;缺点:只能继承实例属性,无法继承原型上的方法(如 sayHi)。
function Parent(name) { this.name = name; this.colors = ['red', 'blue']; } function Child(name, age) { Parent.call(this, name); // 关键:借用父类构造逻辑 this.age = age; } const c1 = new Child('Alice', 25); c1.colors.push('green'); const c2 = new Child('Bob', 30); console.log(c2.colors); // ['red', 'blue'] ← 独立副本 // c1.sayHi(); // ❌ 报错:没有继承原型方法
3. 组合继承(最常用)
结合前两种:原型链继承方法 + 构造函数继承属性。既复用方法,又保证实例属性独立。
优点:功能完整、语义清晰;缺点:父类构造函数被调用两次(一次在设置原型时,一次在子类中 call)。
- 第一次:Child.prototype = new Parent() → 执行 Parent 构造函数
- 第二次:Parent.call(this, …) → 再次执行 Parent 构造函数
4. 寄生组合继承(推荐)
优化组合继承,只调用一次父类构造函数。核心是用 Object.create(Parent.prototype) 创建干净的原型对象,再赋给子类 prototype。
这是 ES6 class 的底层实现逻辑,也是 Babel 编译 extends 时采用的方式。
function inheritPrototype(Child, Parent) { const prototype = Object.create(Parent.prototype); prototype.constructor = Child; Child.prototype = prototype; } function Parent(name) { this.name = name; } Parent.prototype.sayHi = function() { console.log('Hi'); }; function Child(name, age) { Parent.call(this, name); // 只在这里调用 Parent this.age = age; } inheritPrototype(Child, Parent); // 关键:干净地继承原型 const c = new Child('Tom', 28); c.sayHi(); // ✅ 正常输出 console.log(c instanceof Parent); // ✅ true
5. ES6 class extends(语法糖,推荐日常使用)
本质仍是寄生组合继承,但由引擎自动处理,代码更易读、支持 super、静态方法、getter/setter 等。
注意:class 必须用 new 调用,且子类构造函数中必须先调用 super()(否则报错)。
class Parent { constructor(name) { this.name = name; } sayHi() { console.log('Hi'); } } class Child extends Parent { constructor(name, age) { super(name); // 必须!等价于 Parent.call(this, name) this.age = age; } sayAge() { console.log(this.age); } } const c = new Child('Lisa', 22); c.sayHi(); // ✅ c.sayAge(); // ✅
基本上就这些。开发中优先用 class extends;需要兼容老环境或深入理解原理时,掌握寄生组合继承就够了。不复杂但容易忽略细节——比如忘记修复 constructor,或 super() 调用时机不对,都会导致行为异常。