当前位置:首页 > JavaScript

实现继承 js

2026-04-06 22:14:58JavaScript

原型链继承

通过将子类的原型指向父类的实例实现继承。子类实例可以访问父类原型上的属性和方法,但所有子类实例共享父类实例的属性,可能导致修改污染。

function Parent() {
  this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
  console.log('Hello from ' + this.name);
};

function Child() {}
Child.prototype = new Parent(); // 原型链继承
const child = new Child();
child.sayHello(); // 输出: Hello from Parent

构造函数继承

在子类构造函数中调用父类构造函数,通过callapply绑定this。子类实例拥有独立的父类属性,但无法继承父类原型上的方法。

实现继承 js

function Parent(name) {
  this.name = name;
}
function Child(name) {
  Parent.call(this, name); // 构造函数继承
}
const child = new Child('Child');
console.log(child.name); // 输出: Child

组合继承

结合原型链继承和构造函数继承,解决属性共享和原型方法继承的问题。但会调用两次父类构造函数,导致子类原型上存在冗余属性。

实现继承 js

function Parent(name) {
  this.name = name;
}
Parent.prototype.sayHello = function() {
  console.log('Hello from ' + this.name);
};
function Child(name) {
  Parent.call(this, name); // 继承属性
}
Child.prototype = new Parent(); // 继承方法
const child = new Child('Child');
child.sayHello(); // 输出: Hello from Child

寄生组合继承

通过Object.create创建父类原型的副本作为子类原型,避免调用父类构造函数。这是ES5中最理想的继承方式。

function Parent(name) {
  this.name = name;
}
Parent.prototype.sayHello = function() {
  console.log('Hello from ' + this.name);
};
function Child(name) {
  Parent.call(this, name); // 继承属性
}
Child.prototype = Object.create(Parent.prototype); // 继承方法
Child.prototype.constructor = Child; // 修复构造函数指向
const child = new Child('Child');
child.sayHello(); // 输出: Hello from Child

ES6类继承

使用extendssuper语法糖实现继承,底层仍基于寄生组合继承。代码更简洁,支持静态方法继承。

class Parent {
  constructor(name) {
    this.name = name;
  }
  sayHello() {
    console.log('Hello from ' + this.name);
  }
}
class Child extends Parent {
  constructor(name) {
    super(name); // 调用父类构造函数
  }
}
const child = new Child('Child');
child.sayHello(); // 输出: Hello from Child

标签: js
分享给朋友:

相关文章

js实现

js实现

实现 JavaScript 功能的方法 在 JavaScript 中实现特定功能通常涉及多个步骤。以下是常见的实现方法: 基础语法和变量声明 使用 let 或 const 声明变量: let co…

js实现文件下载

js实现文件下载

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

js实现驼峰

js实现驼峰

实现驼峰命名的几种方法 使用正则表达式和字符串替换 通过正则表达式匹配字符串中的特定模式(如下划线或短横线),并将其后的字母转换为大写,同时移除分隔符。 function toCamelCase(s…

js实现防洪

js实现防洪

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

js实现图片

js实现图片

图片加载与显示 在JavaScript中,可以通过Image对象动态加载图片。创建实例后设置src属性触发加载,通过onload回调处理加载完成后的操作: const img = new Ima…

js分页实现

js分页实现

分页的基本原理 分页的核心是通过计算当前页码和数据偏移量,从服务器或本地数据中截取对应范围的数据进行展示。通常需要以下参数:当前页码(currentPage)、每页条数(pageSize)、总数据量(…