javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > JS 继承方式

JS 的继承方式与使用场景对比分析

作者:啊哈哈哈哈哈h

本文介绍了JavaScript中六种主要的继承实现方式及其适用场景,并推荐在现代项目中优先使用ES6的class继承,每种继承方式都有其特点和适用范围,选择合适的继承方式对于编写清晰、高效的JavaScript代码至关重要,感兴趣的朋友一起看看吧

在 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创建的对象共享

特点

场景

五、寄生式继承

实现方式

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"

特点

场景

总结与场景对比

继承方式适用场景现代选择优先级
原型链继承快速实现简单原型链(已过时)⭐️
构造函数继承需要独立实例属性的场景⭐️⭐️
组合继承传统项目兼容性解决方案⭐️⭐️
寄生组合式继承需要高效且标准的继承方案⭐️⭐️⭐️⭐️
ES6 class 继承现代项目开发(Babel转译后兼容性好)⭐️⭐️⭐️⭐️⭐️

实际开发建议

到此这篇关于JS 的继承方式与使用场景的文章就介绍到这了,更多相关JS 继承方式内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文