当前位置:首页 > JavaScript

js实现继承原理

2026-01-30 11:43:15JavaScript

原型链继承

通过将子类的原型对象指向父类的实例实现继承。子类实例可以访问父类原型上的属性和方法,但所有子类实例共享父类实例的属性,可能导致修改污染。

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'

构造函数继承

在子类构造函数中调用父类构造函数,使用callapply改变this指向。可以解决原型链继承的属性共享问题,但无法继承父类原型上的方法。

function Parent(name) {
  this.name = name;
}

function Child(name) {
  Parent.call(this, name); // 构造函数继承
}

const child = new Child('child');
console.log(child.name); // 输出 'child'

组合继承

结合原型链继承和构造函数继承,既继承父类实例属性又继承原型方法。但会调用两次父类构造函数,导致子类原型上存在冗余属性。

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'

原型式继承

基于已有对象创建新对象,类似浅拷贝。Object.create()是规范化实现,适合不需要单独构造函数的场景。

const parent = {
  name: 'parent',
  say: function() {
    console.log(this.name);
  }
};

const child = Object.create(parent); // 原型式继承
child.name = 'child';
child.say(); // 输出 'child'

寄生式继承

在原型式继承基础上增强对象,添加额外方法。与工厂模式类似,无法实现函数复用。

function createChild(parent) {
  const child = Object.create(parent);
  child.newMethod = function() {
    console.log('new method');
  };
  return child;
}

寄生组合式继承

目前最理想的继承方式。通过借用构造函数继承属性,通过原型链混成形式继承方法,只调用一次父类构造函数。

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() {
  console.log(this.name);
};

function Child(name) {
  Parent.call(this, name);
}
inheritPrototype(Child, Parent); // 寄生组合继承

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

ES6 Class继承

使用extends关键字实现语法糖继承,底层仍基于原型链。支持super调用父类构造函数和方法。

js实现继承原理

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'

标签: 原理js
分享给朋友:

相关文章

js实现vue

js实现vue

Vue.js 简介 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。其核心库专注于视图层,易于与其他库或现有项目整合。 实现 Vue.js 的基本步骤 安装 Vue.j…

js实现轮播

js实现轮播

实现轮播图的基本思路 轮播图的核心逻辑是通过定时切换展示的图片或内容,通常结合左右滑动按钮和指示器(小圆点)增强交互性。以下是基于原生JavaScript的实现方法。 HTML结构 构建轮播图的HT…

js实现预览

js实现预览

文件上传预览实现 使用JavaScript实现文件上传预览功能,可以通过FileReader对象读取文件内容并显示预览。以下代码支持图片、文本和PDF文件的预览: // HTML部分需要包含…

js树实现

js树实现

树的基本概念 树是一种非线性的数据结构,由节点和边组成。每个节点包含一个值和指向子节点的引用。树的顶部节点称为根节点,没有子节点的节点称为叶节点。 树的实现方式 在JavaScript中,树可以通过…

js实现图片

js实现图片

图片加载与显示 在JavaScript中,可以通过Image对象动态加载图片。创建实例后设置src属性触发加载,通过onload回调处理加载完成后的操作: const img = new Ima…

js实现下拉菜单

js实现下拉菜单

使用HTML和CSS创建基础结构 HTML部分需要包含一个触发下拉的按钮和隐藏的下拉菜单内容: <div class="dropdown"> <button class="dr…