Javascrpt的继承方式介绍

在 JavaScript 中实现继承主要通过原型链(Prototype Chain)实现,以下是常见的几种继承方式及示例:


1. 原型链继承

通过将子类的原型指向父类的实例实现:

javascript 复制代码
function Parent() {
  this.name = 'Parent';
}
Parent.prototype.say = function() {
  console.log(this.name);
};

function Child() {}
Child.prototype = new Parent(); // 继承父类

const child = new Child();
child.say(); // 输出 "Parent"

缺点:所有子类实例共享父类的引用属性(如数组、对象),修改会相互影响。


2. 构造函数继承

在子类构造函数中调用父类构造函数:

javascript 复制代码
function Parent(name) {
  this.name = name;
  this.colors = ['red', 'blue'];
}

function Child(name) {
  Parent.call(this, name); // 继承父类属性
}

const child1 = new Child('Child1');
child1.colors.push('green'); // 修改不影响其他实例
const child2 = new Child('Child2');
console.log(child2.colors); // ['red', 'blue']

缺点:无法继承父类原型上的方法。


3. 组合继承(经典继承)

结合原型链继承和构造函数继承:

javascript 复制代码
function Parent(name) {
  this.name = name;
}
Parent.prototype.say = function() {
  console.log(this.name);
};

function Child(name) {
  Parent.call(this, name); // 继承属性
}
Child.prototype = new Parent(); // 继承方法

const child = new Child('Child');
child.say(); // 输出 "Child"

缺点 :父类构造函数被调用两次(Parent.callnew Parent())。


4. 寄生组合继承(最优解)

优化组合继承,避免重复调用父类构造函数:

javascript 复制代码
function Parent(name) {
  this.name = name;
}
Parent.prototype.say = function() {
  console.log(this.name);
};

function Child(name) {
  Parent.call(this, name);
}
Child.prototype = Object.create(Parent.prototype); // 核心:创建父类原型的副本
Child.prototype.constructor = Child; // 修复构造函数指向

const child = new Child('Child');
child.say(); // 输出 "Child"

5. ES6 class 继承

使用 extendssuper 关键字(语法糖,底层仍是原型链):

javascript 复制代码
class Parent {
  constructor(name) {
    this.name = name;
  }
  say() {
    console.log(this.name);
  }
}

class Child extends Parent {
  constructor(name) {
    super(name); // 调用父类构造函数
  }
}

const child = new Child('Child');
child.say(); // 输出 "Child"

总结

  • 推荐使用 ES6 class:语法简洁,可读性强。
  • 兼容性要求高时:使用寄生组合继承(ES5 环境)。
  • 避免使用纯原型链或纯构造函数继承:它们各自有明显缺陷。
相关推荐
2401_878454532 分钟前
HTML和CSS的复习2
前端·css·html
We་ct10 分钟前
吃透现代CSS全技术体系
前端·css·css3·sass·postcss·预处理器
ZC跨境爬虫11 分钟前
跟着 MDN 学 HTML day_11:(语义化容器全站重构+独立CSS拆分+字体合规引入)
前端·css·ui·重构·html·edge浏览器
ZC跨境爬虫13 分钟前
跟着 MDN 学 HTML day_10:(超链接核心语法+路径规则)
前端·css·笔记·ui·html·edge浏览器
GISer_Jing16 分钟前
AI原生前端工程化进阶实践:从流式交互架构到端云协同全链路落地
前端·人工智能·后端·学习
被考核重击19 分钟前
Vue响应式原理(下)
前端·javascript·vue.js
ZC跨境爬虫9 小时前
跟着 MDN 学 HTML day_9:(信件语义标记)
前端·css·笔记·ui·html
前端老石人9 小时前
HTML 字符引用完全指南
开发语言·前端·html
matlab_xiaowang9 小时前
Redux 入门:JavaScript 可预测状态管理库
开发语言·javascript·其他·ecmascript
幼儿园技术家9 小时前
前端如何设计权限系统(RBAC / ABAC)?
前端