当前位置:首页 > JavaScript

js实现继承原理

2026-04-04 03:23:08JavaScript

JavaScript 继承的实现原理

JavaScript 的继承基于原型链机制,主要通过原型对象(prototype)实现。以下是常见的几种继承方式及其原理:

原型链继承

通过将子类的原型指向父类的实例实现继承。

function Parent() {
  this.name = 'Parent';
}
Parent.prototype.sayName = function() {
  console.log(this.name);
};

function Child() {}
Child.prototype = new Parent(); // 原型链继承

const child = new Child();
child.sayName(); // 输出 "Parent"
  • 优点:简单直观
  • 缺点:所有子类实例共享父类引用属性

构造函数继承

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

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

function Child(name) {
  Parent.call(this, name); // 构造函数继承
}
Child.prototype = new Parent(); // 原型链继承

const child = new Child('Child');
child.sayName(); // 输出 "Child"
  • 优点:结合两种继承方式的优点
  • 缺点:父类构造函数被调用两次

原型式继承

基于已有对象创建新对象。

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

const child = Object.create(parent);
child.name = 'Child';
child.sayName(); // 输出 "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.sayName = function() {
  console.log(this.name);
};

function Child(name) {
  Parent.call(this, name);
}

inheritPrototype(Child, Parent);

const child = new Child('Child');
child.sayName(); // 输出 "Child"
  • 优点:只调用一次父类构造函数,避免创建多余属性
  • 缺点:实现稍复杂

ES6 class 继承

ES6 引入的 class 语法糖。

js实现继承原理

class Parent {
  constructor(name) {
    this.name = name;
  }
  sayName() {
    console.log(this.name);
  }
}

class Child extends Parent {
  constructor(name) {
    super(name);
  }
}

const child = new Child('Child');
child.sayName(); // 输出 "Child"
  • 优点:语法简洁,更接近传统面向对象语言
  • 缺点:本质仍是原型继承的语法糖

每种继承方式都有其适用场景,理解其原理有助于根据实际需求选择最合适的实现方式。

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

相关文章

js实现验证码

js实现验证码

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

js实现倒计时

js实现倒计时

使用 setInterval 实现倒计时 通过 setInterval 定时器每秒更新剩余时间,适用于简单倒计时场景。 function countdown(seconds, callbac…

js实现全选

js实现全选

实现全选功能的方法 在JavaScript中实现全选功能通常涉及监听全选复选框的点击事件,并根据其状态控制其他复选框的选中状态。以下是几种常见的实现方式: 基础DOM操作实现 通过获取所有目标复选框…

js实现复制功能

js实现复制功能

使用 document.execCommand 方法 这种方法适用于较旧的浏览器,但在现代浏览器中可能被逐步淘汰。通过创建一个临时的 textarea 元素,将文本内容放入其中,然后执行复制命令。…

js分组实现

js分组实现

分组实现方法 在JavaScript中,可以通过多种方式实现数组或对象的分组操作。以下是几种常见的方法: 使用Array.prototype.reduce() 通过reduce方法可以轻松实现数组分…

js实现百叶窗

js实现百叶窗

使用CSS和JavaScript实现百叶窗效果 通过CSS动画和JavaScript事件监听可以实现百叶窗效果。核心思路是将内容区域分割为多个条状元素,通过控制它们的展开/折叠状态来模拟百叶窗。…