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中最常用的继承方式,因为它结合了原型链继承和构造函数继承的优点,既能继承属性,又能继承方法。

相关推荐
小old弟18 分钟前
前端异常隔离方案:Proxy代理、Web Workers和iframe
前端
脑子慢且灵23 分钟前
【Web前端】JS+DOM来实现乌龟追兔子小游戏
java·开发语言·前端·js·dom
TimelessHaze24 分钟前
前端面试必问:深浅拷贝从基础到手写,一篇讲透
前端·trae
CaptainDrake26 分钟前
React 中 key 的作用
前端·javascript·react.js
全栈技术负责人27 分钟前
移动端富文本markdown中表格滚动与页面滚动的冲突处理:Touch 事件 + 鼠标滚轮精确控制方案
前端·javascript·计算机外设
前端拿破轮32 分钟前
从零到一开发一个Chrome插件(二)
前端·面试·github
珍宝商店40 分钟前
Vue.js 中深度选择器的区别与应用指南
前端·javascript·vue.js
天蓝色的鱼鱼1 小时前
Next.js 预渲染完全指南:SSG vs SSR,看完秒懂!
前端·next.js
月出1 小时前
无限循环滚动条 - 左出右进
前端
aiwery1 小时前
实现带并发限制的 Promise 调度器
前端·算法