当前位置:首页 > JavaScript

js如何实现继承

2026-04-03 18:31:10JavaScript

原型链继承

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

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(); // 第二次调用
Child.prototype.constructor = Child;

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.sayHi = function() {
    console.log('Hi');
  };
  return child;
}

const parent = { name: 'parent' };
const child = createChild(parent);

寄生组合式继承

目前最理想的继承方式,通过Object.create()减少父类构造函数的调用次数,同时保持原型链完整。

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"

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实现验证码

js实现验证码

实现验证码的JavaScript方法 生成随机验证码 使用Math.random()生成随机字符串,结合数字和字母: function generateCaptcha() { const cha…

js 实现vue模板

js 实现vue模板

实现 Vue 模板的 JavaScript 方法 通过原生 JavaScript 可以实现类似 Vue 的模板渲染功能,主要包括数据绑定、指令处理和模板解析。以下是核心实现思路: 数据绑定与…

vue如何实现曲线图

vue如何实现曲线图

使用 ECharts 实现曲线图 在 Vue 项目中安装 ECharts 依赖: npm install echarts --save 引入 ECharts 并创建基础图表组件: <temp…

js实现vr

js实现vr

使用WebXR API实现VR体验 WebXR是浏览器中实现VR和AR体验的标准API,它取代了早期的WebVR。现代浏览器如Chrome、Edge和Firefox已支持WebXR。 // 初始化W…

js实现二叉树

js实现二叉树

二叉树的基本概念 二叉树是一种树形数据结构,每个节点最多有两个子节点,分别称为左子节点和右子节点。二叉树的常见操作包括插入、删除、遍历等。 二叉树的节点定义 在JavaScript中,二叉树的节点可…

h5页面如何实现

h5页面如何实现

实现H5页面的方法 H5页面是基于HTML5技术的网页,通常用于移动端和响应式设计。以下是实现H5页面的关键步骤和技术要点。 基础结构 使用HTML5的DOCTYPE声明作为页面的起始。HTML5简…