当前位置:首页 > JavaScript

js 实现 extends

2026-04-06 02:55:28JavaScript

实现继承的方式

在 JavaScript 中,可以通过多种方式实现继承。以下是几种常见的方法:

原型链继承

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

js 实现 extends

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

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

function Child() {}

Child.prototype = new Parent();
Child.prototype.constructor = Child;

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

构造函数继承

在子类的构造函数中调用父类的构造函数,使用 callapply 方法。

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

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

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

组合继承

结合原型链继承和构造函数继承的优点。

js 实现 extends

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

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

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

Child.prototype = new Parent();
Child.prototype.constructor = Child;

const child = new Child('Child', 10);
child.sayName(); // 输出 'Child'

寄生组合继承

优化组合继承,避免重复调用父类构造函数。

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

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

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

Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;

const child = new Child('Child', 10);
child.sayName(); // 输出 'Child'

ES6 的 class 继承

使用 classextends 关键字实现继承。

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

  sayName() {
    console.log(this.name);
  }
}

class Child extends Parent {
  constructor(name, age) {
    super(name);
    this.age = age;
  }
}

const child = new Child('Child', 10);
child.sayName(); // 输出 'Child'

选择继承方式的建议

  • 原型链继承简单但可能导致引用类型共享问题。
  • 构造函数继承无法继承父类原型上的方法。
  • 组合继承是较为常用的方式,但会调用两次父类构造函数。
  • 寄生组合继承是组合继承的优化版本,推荐使用。
  • ES6 的 class 继承语法简洁,推荐在现代项目中使用。

标签: jsextends
分享给朋友:

相关文章

js实现文件下载

js实现文件下载

使用 a 标签下载文件 通过动态创建 a 标签并设置 download 属性实现文件下载。适用于已知文件 URL 或 Blob 数据的情况。 function downloadFile(url, f…

js实现选题

js实现选题

实现选题功能的JavaScript方法 基础实现方案 使用数组存储选项,通过随机索引选取: const options = ['选项A', '选项B', '选项C', '选项D']; const r…

js实现授权

js实现授权

授权流程设计 授权流程通常涉及前端与后端的交互,常见方案包括OAuth2.0、JWT等。以JWT为例的典型流程: 用户提交凭证(如用户名密码)到认证服务 服务端验证通过后生成包含用户信息的JWT令牌…

js实现排序

js实现排序

数组排序方法 JavaScript提供了内置的sort()方法用于数组排序。默认情况下,sort()将元素转换为字符串并按照Unicode码点排序。对于数字排序,需传入比较函数。 const num…

js 实现mvc

js 实现mvc

MVC 模式简介 MVC(Model-View-Controller)是一种软件设计模式,将应用程序分为三个核心组件:模型(Model)处理数据和业务逻辑,视图(View)负责展示数据,控制器(Con…

js实现vue模板

js实现vue模板

使用纯 JavaScript 实现 Vue 模板功能 要实现类似 Vue 的模板功能,可以通过以下步骤完成: 1. 数据绑定与响应式更新 通过 Object.defineProperty 或 Pr…