侧边栏壁纸
博主头像
Fonda's Lab 博主等级

关山难越,谁悲失路之人?萍水相逢,尽是他乡之客。

  • 累计撰写 49 篇文章
  • 累计创建 27 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

ES5实现继承的几种方式

LouisFonda
2024-05-27 / 0 评论 / 0 点赞 / 22 阅读 / 0 字 / 正在检测是否收录...

ES5实现继承的几种方式

1. 构造函数继承

构造函数继承通过在子类构造函数中调用父类构造函数,实现继承父类的属性。它无法继承父类的原型方法。

function Parent(name) {
  this.name = name;
}

function Child(name, age) {
  Parent.call(this, name); // 调用 Parent 构造函数
  this.age = age;
}

const child = new Child('Alice', 25);
console.log(child.name); // 'Alice'
console.log(child.age);  // 25

2. 原型继承

原型继承通过将子类的原型对象指向父类的实例,实现继承父类的属性和方法。

function Parent(name) {
  this.name = name;
}

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

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

Child.prototype = new Parent(); // 继承 Parent 的原型
Child.prototype.constructor = Child; // 修复构造函数指向

const child = new Child('Bob', 30);
console.log(child.name); // 'Bob'
console.log(child.age);  // 30
child.sayHello();        // 'Hello, Bob'

3. 组合继承

组合继承结合了构造函数继承和原型继承的优点,实现了属性和方法的继承。它是最常用的继承方式。

function Parent(name) {
  this.name = name;
}

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

function Child(name, age) {
  Parent.call(this, name); // 构造函数继承
  this.age = age;
}

Child.prototype = new Parent(); // 原型继承
Child.prototype.constructor = Child; // 修复构造函数指向

const child = new Child('Charlie', 35);
console.log(child.name); // 'Charlie'
console.log(child.age);  // 35
child.sayHello();        // 'Hello, Charlie'

4. 寄生组合继承

寄生组合继承是对组合继承的优化,避免了在原型链上创建多余的父类实例。它是实现继承的最佳方式。

function Parent(name) {
  this.name = name;
}

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

function Child(name, age) {
  Parent.call(this, name); // 构造函数继承
  this.age = age;
}

function inheritPrototype(child, parent) {
  var prototype = Object.create(parent.prototype); // 创建父类原型的一个副本
  prototype.constructor = child; // 修复构造函数指向
  child.prototype = prototype; // 将副本赋值给子类的原型
}

inheritPrototype(Child, Parent);

const child = new Child('Dave', 40);
console.log(child.name); // 'Dave'
console.log(child.age);  // 40
child.sayHello();        // 'Hello, Dave'

总结

  • 构造函数继承:只能继承父类的属性,无法继承原型方法。
  • 原型继承:通过修改子类原型指向父类实例来实现继承,能继承属性和方法。
  • 组合继承:结合了构造函数继承和原型继承的优点,避免了各自的缺点。
  • 寄生组合继承:在组合继承的基础上进行优化,避免了创建多余的父类实例,是实现继承的最佳方式。
    通过这些方式,可以在 ES5 中实现不同的继承模式,选择合适的方式可以根据具体的需求和代码结构。
0

评论区