javaScript继承有4种常用方式:1.原型链继承共享引用属性且无法传参;2.构造函数继承可传参但无法复用原型方法;3.组合继承兼顾两者但父构造函数被调用两次;4.寄生组合式继承只调用一次父构造函数,是目前最推荐的手写方式。

javascript 中实现继承主要有 4 种常用方式,核心区别在于 如何让子类访问父类的属性和方法,以及 原型链、构造函数、实例属性的归属是否合理。没有“最好”的方式,只有更合适场景的选择。
1. 原型链继承
把父类的实例赋给子类的 prototype。
function Parent() { this.name = 'parent'; } Parent.prototype.say = function() { return 'hello'; }; function Child() {} Child.prototype = new Parent(); // 关键:继承原型 Child.prototype.constructor = Child; // 修复 constructor 指向
red”>注意:所有子类实例共享父类实例上的引用类型属性(比如数组、对象),修改会影响其他实例;无法向父类构造函数传参。
2. 构造函数继承(借用构造函数)
在子类构造函数中用 call 或 apply 调用父类构造函数。
立即学习“Java免费学习笔记(深入)”;
function Parent(name) { this.name = name; this.colors = ['red']; } function Child(name) { Parent.call(this, name); // 关键:继承实例属性 }
优点:可传参,每个实例有独立的属性(避免引用共享)。缺点:只能继承实例属性,父类原型上的方法不可复用(子类实例不能调用 say())。
3. 组合继承(原型链 + 构造函数)
最常用、较均衡的方式:用构造函数继承实例属性,用原型链继承方法。
function Parent(name) { this.name = name; this.colors = ['red']; } Parent.prototype.say = function() { return 'hello'; }; function Child(name, age) { Parent.call(this, name); // 第一次调用 Parent this.age = age; } Child.prototype = new Parent(); // 第二次调用 Parent —— 缺点在此 Child.prototype.constructor = Child;
✅ 有独立属性、可传参、能复用方法。但父类构造函数被调用了两次(一次在子类实例创建时,一次在设置原型时),略低效。
4. 寄生组合式继承(推荐)
优化组合继承,只调用一次父类构造函数,是 es6 class 继承背后的原理。
function inheritPrototype(Child, Parent) { const proto = Object.create(Parent.prototype); proto.constructor = Child; Child.prototype = proto; } function Child(name, age) { Parent.call(this, name); this.age = age; } inheritPrototype(Child, Parent); // 关键:干净地设置原型
✅ 避免重复调用父构造函数,属性与方法分离清晰,是目前最推荐的手写继承模式。
ES6 的 class extends 本质就是寄生组合式继承的语法糖,底层仍靠原型链和 Object.setPrototypeOf 等实现。不复杂但容易忽略细节,用对方式才能写出健壮可维护的代码。