
在 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"
特点:
场景:
实现方式:
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); // 方法继承
特点:
场景:
实现方式:
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转译后兼容性好) | ⭐️⭐️⭐️⭐️⭐️ |
实际开发建议:
class
继承(清晰、易维护,Babel 转译后底层使用寄生组合式继承)到此这篇关于JS 的继承方式与使用场景的文章就介绍到这了,更多相关JS 继承方式内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!