ES5怎么实现继承

在 ES5 中,实现继承通常有以下几种方法:

1. 原型链继承

这是最常用的继承方式,通过设置一个构造函数的原型为另一个构造函数的实例来实现。

javascript 复制代码
function Parent() {
  this.name = 'Parent';
}
Parent.prototype.say = function() {
  console.log('Hello from parent');
};

function Child() {
  Parent.call(this); // 继承Parent构造函数的属性
  this.name = 'Child';
}
Child.prototype = new Parent(); // 继承Parent原型
Child.prototype.constructor = Child; // 修正构造函数指向

var childInstance = new Child();
console.log(childInstance.name); // 输出 "Child"
childInstance.say(); // 输出 "Hello from parent"

2. 构造函数继承

直接在子构造函数中调用父构造函数。

javascript 复制代码
function Parent(name) {
  this.name = name;
}
Parent.prototype.say = function() {
  console.log('Hello from parent');
};

function Child(name) {
  Parent.call(this, name); // 继承Parent构造函数的属性
  this.name = name;
}
var childInstance = new Child('Child');
console.log(childInstance.name); // 输出 "Child"
childInstance.say(); // 输出 "Hello from parent"

3. 组合继承(推荐)

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

javascript 复制代码
function Parent(name) {
  this.name = name;
  this.colors = ['red', 'blue', 'green'];
}
Parent.prototype.say = function() {
  console.log('Hello from parent');
};

function Child(name, age) {
  Parent.call(this, name); // 继承Parent构造函数的属性
  this.age = age;
}
Child.prototype = new Parent(); // 继承Parent原型
Child.prototype.constructor = Child; // 修正构造函数指向

Child.prototype.sayAge = function() {
  console.log('Age: ' + this.age);
};

var childInstance = new Child('Child', 10);
console.log(childInstance.name); // 输出 "Child"
childInstance.say(); // 输出 "Hello from parent"
childInstance.sayAge(); // 输出 "Age: 10"

4. 寄生式继承

创建一个空函数作为父类型,将子类型的方法添加到这个空函数的原型上。

javascript 复制代码
function Parent(name) {
  this.name = name;
}
Parent.prototype.say = function() {
  console.log('Hello from parent');
};

function inheritPrototype(Child, Parent) {
  var prototype = Object.create(Parent.prototype);
  prototype.constructor = Child;
  Child.prototype = prototype;
}

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

Child.prototype.sayAge = function() {
  console.log('Age: ' + this.age);
};

var childInstance = new Child('Child', 10);
console.log(childInstance.name); // 输出 "Child"
childInstance.say(); // 输出 "Hello from parent"
childInstance.sayAge(); // 输出 "Age: 10"

这些方法各有优缺点,组合继承是ES5中最常用的继承方式,因为它结合了原型链继承和构造函数继承的优点,既能继承属性,又能继承方法。

相关推荐
小高0074 分钟前
2026 年,只会写 div 和 css 的前端将彻底失业
前端·javascript·vue.js
Anita_Sun4 分钟前
Lodash 源码解读与原理分析 - Lodash 原型链的完整结构
前端
梁森的掘金4 分钟前
Frida Hook 流程
前端
www_stdio6 分钟前
Git 提交AI神器:用大模型帮你写出规范的 Commit Message
前端·javascript·react.js
陈随易7 分钟前
Bun v1.3.6发布,内置tar解压缩,各方面提速又提速
前端·后端
双向337 分钟前
【AIGC爆款内容生成全攻略:如何用AI颠覆内容创作效率?】
前端
陈_杨15 分钟前
前端成功转鸿蒙开发者真实案例,教大家如何开发鸿蒙APP-- 卡片编辑功能
前端·harmonyos
Swift社区20 分钟前
Flutter 的异步问题,为什么和前端 Promise 问题高度相似?
前端·flutter
程序员Agions20 分钟前
AI 编程的"效率幻觉":为什么用了 Cursor 之后,你反而更累了?
前端·ai编程
Android技术之家23 分钟前
在手机上跑大模型?Google AI Edge Gallery 开源项目深度解析
前端·人工智能·edge·开源