当前位置:首页 > JavaScript

js extends 实现

2026-03-15 08:30:29JavaScript

extends 的基本用法

在 JavaScript 中,extends 关键字用于实现类之间的继承。子类通过 extends 继承父类的属性和方法。

class Parent {
  constructor(name) {
    this.name = name;
  }
  greet() {
    console.log(`Hello, ${this.name}`);
  }
}

class Child extends Parent {
  constructor(name, age) {
    super(name); // 调用父类的构造函数
    this.age = age;
  }
  greet() {
    super.greet(); // 调用父类的方法
    console.log(`I am ${this.age} years old`);
  }
}

const child = new Child('Alice', 10);
child.greet();

super 关键字的作用

super 用于在子类中调用父类的构造函数或方法。必须在子类构造函数中使用 super() 后才能使用 this

js extends 实现

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

class Child extends Parent {
  constructor(value, extra) {
    super(value); // 必须调用
    this.extra = extra;
  }
}

继承内置类型

extends 可以继承 JavaScript 内置类型,如 Array、Error 等。

js extends 实现

class CustomArray extends Array {
  isEmpty() {
    return this.length === 0;
  }
}

const arr = new CustomArray(1, 2, 3);
console.log(arr.isEmpty()); // false

静态方法的继承

静态方法也会被继承,可以通过 super 在子类中调用父类的静态方法。

class Parent {
  static staticMethod() {
    return 'Parent static';
  }
}

class Child extends Parent {
  static staticMethod() {
    return super.staticMethod() + ' + Child static';
  }
}

console.log(Child.staticMethod()); // "Parent static + Child static"

检查继承关系

使用 instanceof 可以检查对象的继承关系。

class Parent {}
class Child extends Parent {}

const child = new Child();
console.log(child instanceof Parent); // true

注意事项

  • 子类必须在 constructor 中调用 super(),除非子类没有显式定义构造函数
  • 箭头函数没有自己的 this,不能用作构造函数,也不能用 extends 继承
  • 可以继承普通的构造函数(非 class),但有一些限制
function ParentFunc(name) {
  this.name = name;
}
ParentFunc.prototype.greet = function() {
  console.log(`Hello, ${this.name}`);
};

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

const child = new Child('Bob', 12);
child.greet(); // "Hello, Bob"

标签: jsextends
分享给朋友:

相关文章

vue.js实现轮播

vue.js实现轮播

Vue.js 实现轮播功能 使用第三方库(推荐) Vue.js 生态中有许多成熟的轮播组件库,例如 vue-awesome-swiper 或 swiper,它们功能丰富且易于集成。 安装 swipe…

js实现轮播图

js实现轮播图

基础轮播图实现 使用HTML、CSS和JavaScript实现一个简单的自动轮播图。HTML结构包含一个容器和多个图片项。 <div class="slider"> <div…

js 进度条的实现

js 进度条的实现

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

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…

js实现目录

js实现目录

实现目录的基本思路 在JavaScript中实现目录功能通常涉及以下几个核心步骤:解析文档中的标题元素(如h1-h6),动态生成目录结构,并添加交互逻辑(如点击跳转)。以下是具体实现方法: 解析标题…

js实现 功能

js实现 功能

在 JavaScript 中实现功能通常涉及多个关键步骤,具体取决于功能需求。以下是常见功能的实现方法和示例: 基本功能实现 使用函数封装逻辑是最直接的方式。例如,实现一个计算两数之和的函数: f…