在 javascript 中,继承的实现方式主要有以下几种,每种方式适用于不同的场景:
一、原型链继承
实现方式:
function parent() { this.name = 'parent'; } parent.prototype.say = function() { return this.name; }; function child() {} child.prototype = new parent(); // 原型继承关键 const child = new child(); child.say(); // 输出 "parent"
特点:
- 子类实例通过原型链访问父类属性和方法
- 问题:父类的引用类型属性会被所有子类实例共享
场景:
- 简单继承结构,无引用类型共享问题需求的场景
- 老项目快速实现继承(现代开发不推荐优先使用)
二、构造函数继承
实现方式:
function parent(name) { this.name = name; } function child(name) { parent.call(this, name); // 构造函数继承关键 } const child = new child('child'); child.name; // 输出 "child"
特点:
- 将父类属性复制到子类实例
- 优点:解决引用属性共享问题
- 缺陷:无法继承父类原型上的方法
场景:
- 需要 实例属性独立性的场景(如每个对象需要独立状态)
- 不支持子类复用父类原型方法(若无需复用则合适)
三、组合继承(经典继承)
实现方式:
function parent(name) { this.name = name; } parent.prototype.say = function() { return this.name }; function child(name) { parent.call(this, name); // 第1次调用父类构造函数 } child.prototype = new parent(); // 第2次调用父类构造函数(问题根源) child.prototype.constructor = child; const child = new child('child'); child.say(); // 输出 "child"
特点:
- 结合原型链继承(方法继承)和构造函数继承(属性继承)
- 缺陷:父类构造函数被调用两次,子类原型中存在冗余属性
场景:
- 传统项目的常规继承需求(es6 出现前的常见方案)
- 需要同时满足方法复用和实例属性独立的场景
四、原型式继承
实现方式:
const parent = { name: 'parent', friends: ['alice'] }; const child = object.create(parent); // 核心api child.name = 'child'; child.friends.push('bob'); // friends被所有基于parent创建的对象共享
特点:
- 类似于对象浅拷贝
- 问题:引用类型属性共享(与原型链相同)
场景:
- 简单对象继承需求(无构造函数存在的场景)
- 原型链的极简替代方案(如旧环境无
object.create
时的polyfill
)
五、寄生式继承
实现方式:
function createchild(parent) { const obj = object.create(parent); obj.sayhi = () => 'hi'; // 添加额外方法 return obj; } const child = createchild({ name: 'parent' });
特点:
- 工厂模式增强对象
- 缺陷:方法无法复用,类似构造函数问题
场景:
- 需要给对象快速扩展额外方法的场景
- 不适合大型继承结构(复用性差)
六、寄生组合式继承(最优解)
实现方式:
function inheritprototype(child, parent) { const prototype = object.create(parent.prototype); // 创建父类原型的副本 prototype.constructor = child; // 修复构造函数指向 child.prototype = prototype; // 赋值给子类原型 } function parent(name) { this.name = name; } parent.prototype.say = function() { return this.name; }; function child(name) { parent.call(this, name); // 属性继承 } inheritprototype(child, parent); // 方法继承
特点:
- 只调用一次父类构造函数,避免组合继承的冗余问题
- 保留完整的原型链结构
场景:
- 现代项目推荐的标准继承方式
- 适用于所有复杂继承需求(效率最高)
七、es6 class 继承
实现方式:
class parent { constructor(name) { this.name = name } say() { return this.name } } class child extends parent { // extends 关键字 constructor(name) { super(name); // super调用父类构造函数 } } const child = new child('child'); child.say(); // 输出 "child"
特点:
- 语法糖,本质基于原型和寄生组合式继承
- 支持
static
、super
等特性
场景:
- 现代项目首选方式
- 需要清晰类结构、继承关系明确的场景
总结与场景对比
继承方式 | 适用场景 | 现代选择优先级 |
---|---|---|
原型链继承 | 快速实现简单原型链(已过时) | ⭐️ |
构造函数继承 | 需要独立实例属性的场景 | ⭐️⭐️ |
组合继承 | 传统项目兼容性解决方案 | ⭐️⭐️ |
寄生组合式继承 | 需要高效且标准的继承方案 | ⭐️⭐️⭐️⭐️ |
es6 class 继承 | 现代项目开发(babel转译后兼容性好) | ⭐️⭐️⭐️⭐️⭐️ |
实际开发建议:
- 优先使用 es6
class
继承(清晰、易维护,babel 转译后底层使用寄生组合式继承) - 旧项目维护时根据现有模式选择组合或寄生组合继承
4️⃣原型式/寄生式继承主要用于对象克隆而非类继承场景
到此这篇关于js 的继承方式与使用场景的文章就介绍到这了,更多相关js 继承方式内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论