返回

剖析JS继承方式,解析六种经典模式让开发如虎添翼

前端

  1. 原型链继承

原型链继承是最简单、最直接的JavaScript继承方式。在原型链继承中,子类通过继承父类的原型对象来获取父类的属性和方法。

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

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

function Child() {
  this.name = 'child';
}

Child.prototype = new Parent(); // 继承父类原型对象

const child = new Child();
child.sayHello(); // Hello, I am child

2. 构造函数继承

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

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

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

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

Child.prototype = new Parent(); // 继承父类原型对象

const child = new Child('child');
child.sayHello(); // Hello, I am child

3. 组合继承

组合继承是原型链继承和构造函数继承的结合。组合继承可以同时继承父类的原型对象和构造函数。

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

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

function Child(name) {
  // 调用父类构造函数
  Parent.call(this, name);
  // 继承父类原型对象
  this.__proto__ = Parent.prototype;
}

const child = new Child('child');
child.sayHello(); // Hello, I am child

4. 原型式继承

原型式继承是一种简单、高效的JavaScript继承方式。在原型式继承中,子类通过复制父类对象来继承父类的属性和方法。

const parent = {
  name: 'parent',
  sayHello: function() {
    console.log('Hello, I am ' + this.name);
  }
};

const child = Object.create(parent); // 复制父类对象
child.name = 'child';

child.sayHello(); // Hello, I am child

5. 寄生式继承

寄生式继承是一种巧妙的JavaScript继承方式。在寄生式继承中,子类通过一个中间函数来继承父类的属性和方法。

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

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

function Child(name) {
  // 创建一个中间函数
  const intermediateFunction = function() {};
  // 中间函数的原型指向父类对象
  intermediateFunction.prototype = new Parent(name);
  // 子类对象指向中间函数的实例
  this.__proto__ = new intermediateFunction();
}

const child = new Child('child');
child.sayHello(); // Hello, I am child

6. 寄生组合式继承

寄生组合式继承是寄生式继承和组合继承的结合。寄生组合式继承可以同时继承父类的原型对象和构造函数,同时避免了构造函数继承中的重复代码。

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

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

function Child(name) {
  // 创建一个中间函数
  const intermediateFunction = function() {};
  // 中间函数的原型指向父类对象
  intermediateFunction.prototype = new Parent(name);
  // 子类对象指向中间函数的实例
  this.__proto__ = new intermediateFunction();
  // 调用父类构造函数
  Parent.call(this, name);
}

const child = new Child('child');
child.sayHello(); // Hello, I am child

总结

JavaScript提供了多种继承方式,每种方式都有其独特的特点和适用场景。开发人员可以根据实际需要选择合适的继承方式,以提高代码的可维护性和可扩展性。

在实际开发中,组合继承和寄生组合式继承是两种比较常用的继承方式。组合继承可以同时继承父类的原型对象和构造函数,而寄生组合式继承可以避免构造函数继承中的重复代码。

希望本文对您理解JavaScript继承方式有所帮助。如果您还有其他问题,欢迎随时提出。