当前位置:首页 > 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 实现vue

js 实现vue

实现 Vue 的核心功能 在 JavaScript 中实现 Vue 的核心功能需要模拟数据绑定、虚拟 DOM 和响应式系统。以下是一个简化版的实现思路: 响应式系统 通过 Object.defin…

js实现

js实现

JavaScript 实现方法 JavaScript 是一种广泛使用的编程语言,适用于网页开发、服务器端编程以及移动应用开发。以下是几种常见的 JavaScript 实现方法: 网页交互功能 使用…

vue实现js休眠

vue实现js休眠

Vue 中实现 JavaScript 休眠 在 Vue 中实现 JavaScript 休眠通常需要使用异步方式,以避免阻塞主线程。以下是几种常见方法: 使用 setTimeout 和 Pro…

js实现继承

js实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Parent…

js 实现倒计时

js 实现倒计时

实现倒计时的基本方法 使用 JavaScript 实现倒计时可以通过 setInterval 或 setTimeout 结合日期计算来完成。以下是两种常见实现方式。 使用 setInterval…

js 进度条的实现

js 进度条的实现

使用 HTML 和 CSS 创建基础进度条 HTML 结构可以简单使用一个 div 元素作为容器,内部嵌套另一个 div 表示进度: <div class="progress-containe…