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

实现拖拽的基本步骤 使用JavaScript实现拖拽功能需要监听鼠标事件,包括mousedown、mousemove和mouseup。以下是实现的基本逻辑: const draggableEleme…

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https://…

js实现图片上传

js实现图片上传

图片上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现图片上传功能。HTML部分需要创建一个文件选择输入框和一个用于…

js防抖和节流实现

js防抖和节流实现

防抖(Debounce)的实现 防抖的核心思想是在事件被触发后,延迟执行回调函数。如果在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口大小调整等场景。 function debounce…

js实现投球

js实现投球

实现投球动画的基本思路 使用JavaScript和CSS动画结合的方式模拟投球效果。核心是通过改变元素的位置、旋转和缩放属性,配合定时器或CSS过渡实现平滑动画。 创建基础HTML结构 <di…

js实现密码

js实现密码

密码强度验证 使用正则表达式验证密码强度是一种常见方法。以下代码检查密码是否包含大小写字母、数字和特殊字符,且长度至少为8位: function checkPasswordStrength(pass…