当前位置:首页 > JavaScript

js实现extends

2026-02-01 03:41:25JavaScript

实现 JavaScript 的 extends 功能

JavaScript 中实现继承可以通过原型链和 class 语法来实现 extends 的功能。以下是两种常见的方法:

js实现extends

使用 ES6 的 classextends

ES6 引入了 classextends 关键字,使得继承更加直观和易于理解。

js实现extends

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

  greet() {
    console.log(`Hello, ${this.name}!`);
  }
}

class Child extends Parent {
  constructor(name, age) {
    super(name); // 调用父类的 constructor
    this.age = age;
  }

  greet() {
    super.greet(); // 调用父类的 greet 方法
    console.log(`I am ${this.age} years old.`);
  }
}

const child = new Child('Alice', 10);
child.greet();
// 输出:
// Hello, Alice!
// I am 10 years old.

使用原型链实现继承(ES5 及之前)

在 ES5 及之前的版本中,可以通过原型链手动实现继承。

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

Parent.prototype.greet = function() {
  console.log(`Hello, ${this.name}!`);
};

function Child(name, age) {
  Parent.call(this, name); // 调用父类构造函数
  this.age = age;
}

// 设置原型链
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;

// 子类方法
Child.prototype.greet = function() {
  Parent.prototype.greet.call(this); // 调用父类方法
  console.log(`I am ${this.age} years old.`);
};

const child = new Child('Bob', 12);
child.greet();
// 输出:
// Hello, Bob!
// I am 12 years old.

使用 Object.setPrototypeOf

另一种方式是使用 Object.setPrototypeOf 动态设置原型链。

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

Parent.prototype.greet = function() {
  console.log(`Hello, ${this.name}!`);
};

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

// 设置原型链
Object.setPrototypeOf(Child.prototype, Parent.prototype);

Child.prototype.greet = function() {
  Parent.prototype.greet.call(this);
  console.log(`I am ${this.age} years old.`);
};

const child = new Child('Charlie', 8);
child.greet();
// 输出:
// Hello, Charlie!
// I am 8 years old.

注意事项

  • 使用 classextends 是推荐的方式,代码更清晰且易于维护。
  • 手动设置原型链时,需确保正确调用父类构造函数(如 Parent.call(this))并修复 constructor 属性。
  • 避免直接修改 __proto__,使用 Object.createObject.setPrototypeOf 更安全。

以上方法可以根据需求选择适合的方式实现 JavaScript 的继承功能。

标签: jsextends
分享给朋友:

相关文章

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽功能。以下是核心代码逻辑: const draggableElement = document.…

js实现图片轮播

js实现图片轮播

实现基础图片轮播 使用HTML、CSS和JavaScript创建一个简单的图片轮播。HTML部分定义轮播容器和图片,CSS设置样式和动画效果,JavaScript处理轮播逻辑。 <div cl…

原生js实现轮播图

原生js实现轮播图

基本结构搭建 HTML部分需要包含轮播图容器、图片列表及导航按钮。结构示例如下: <div class="slider-container"> <div class="slid…

js实现图表

js实现图表

在JavaScript中实现图表通常使用流行的图表库,以下是几种常见的方法和工具: 使用Chart.js Chart.js是一个简单灵活的库,适合快速生成响应式图表。安装方式包括CDN引入或npm安…

js树实现

js树实现

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

链表实现js

链表实现js

链表的基本概念 链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和一个指向下一个节点的指针(单向链表)或两个指针(双向链表)。与数组不同,链表在内存中非连续存储,插入和删除操作更高效,但随机…