返回

万花筒般的JavaScript ES5实现继承方式大盘点

前端

JavaScript ES5实现继承的多种方式大盘点

继承是面向对象编程的重要概念之一,它允许新创建的类从已有类继承属性和方法,从而实现代码的重用和扩展。在JavaScript ES5中,主要有以下几种方式可以实现继承:

1. 原型链继承

原型链继承是JavaScript中最常用的继承方式,也是最简单的一种。在这种继承方式中,子类通过其原型对象继承父类属性和方法。当子类实例化时,它会自动获得父类原型对象中的所有属性和方法。

原型链继承的实现方法如下:

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

Parent.prototype.greet = function() {
  console.log(`Hello, I'm ${this.name}!`);
};

function Child() {
  this.name = "Child";
}

// 这里通过 Child.prototype = new Parent()实现了原型链继承
Child.prototype = new Parent();

const child = new Child();

child.greet(); // 输出: Hello, I'm Child!

2. 构造函数继承

构造函数继承也是一种常见的继承方式。在构造函数继承中,子类通过调用父类构造函数的方式来继承父类属性和方法。

构造函数继承的实现方法如下:

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

Parent.prototype.greet = function() {
  console.log(`Hello, I'm ${this.name}!`);
};

function Child(name) {
  // 这里通过 Parent.call(this, name)实现了构造函数继承
  Parent.call(this, name);
}

// Child.prototype = new Parent();

const child = new Child("Child");

child.greet(); // 输出: Hello, I'm Child!

3. 组合继承

组合继承是原型链继承和构造函数继承的结合。它通过调用父类构造函数的方式来继承父类属性和方法,同时通过修改子类原型对象的方式来继承父类原型对象中的属性和方法。

组合继承的实现方法如下:

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

Parent.prototype.greet = function() {
  console.log(`Hello, I'm ${this.name}!`);
};

function Child(name) {
  // 这里通过 Parent.call(this, name)实现了构造函数继承
  Parent.call(this, name);

  // 这里通过 Child.prototype = new Parent()实现了原型链继承
  Child.prototype = new Parent();
}

const child = new Child("Child");

child.greet(); // 输出: Hello, I'm Child!

4. 原型式继承

原型式继承是一种不使用构造函数的继承方式。在这种继承方式中,子类通过直接复制父类原型对象的方式来继承父类属性和方法。

原型式继承的实现方法如下:

const parent = {
  name: "Parent",
  greet: function() {
    console.log(`Hello, I'm ${this.name}!`);
  }
};

const child = Object.create(parent);

child.name = "Child";

child.greet(); // 输出: Hello, I'm Child!

5. 寄生式继承

寄生式继承是一种不使用原型链和构造函数的继承方式。在这种继承方式中,子类通过创建一个新对象,并将其指向父类原型对象的方式来继承父类属性和方法。

寄生式继承的实现方法如下:

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

Parent.prototype.greet = function() {
  console.log(`Hello, I'm ${this.name}!`);
};

function Child(name) {
  // 创建一个新对象,并将其指向父类原型对象
  const child = Object.create(Parent.prototype);

  // 设置子类属性
  child.name = name;

  // 返回子类对象
  return child;
}

const child = new Child("Child");

child.greet(); // 输出: Hello, I'm Child!

总结

以上五种方式都是JavaScript ES5中实现继承的常用方法。每种方法都有其自身的特点和适用场景。在实际开发中,可以根据具体需求选择合适的方法来实现继承。