返回

JS进阶之道:5种继承实现方式剖析

前端

JavaScript中的原型链

在JavaScript中,原型链是一条对象到对象的链,它从对象本身开始,并一直延伸到Object原型对象。每个对象都有一个原型对象,该对象定义了该对象可以访问的属性和方法。当对象尝试访问一个不存在于自身属性中的属性或方法时,它会沿着原型链向上查找,直到找到该属性或方法为止。

JavaScript中的5种继承方案

JavaScript支持多种继承方式,包括:

  1. 原型继承 :原型继承是JavaScript中最基本、最简单的继承方式。它允许您通过创建一个新对象并将其原型对象设置为另一个对象来实现继承。例如:
function Person(name) {
  this.name = name;
}

Person.prototype.sayHello = function() {
  console.log(`Hello, my name is ${this.name}.`);
};

function Student(name, major) {
  Person.call(this, name);
  this.major = major;
}

Student.prototype = Object.create(Person.prototype);

const student = new Student('John', 'Computer Science');

student.sayHello(); // 输出:Hello, my name is John.
  1. 构造函数继承 :构造函数继承是一种更复杂的继承方式,它允许您通过在子类构造函数中调用父类构造函数来实现继承。例如:
function Person(name) {
  this.name = name;
}

function Student(name, major) {
  Person.call(this, name);
  this.major = major;
}

const student = new Student('John', 'Computer Science');

console.log(student.name); // 输出:John
console.log(student.major); // 输出:Computer Science
  1. 组合继承 :组合继承是原型继承和构造函数继承的结合。它允许您通过同时使用原型继承和构造函数继承来实现继承。例如:
function Person(name) {
  this.name = name;
}

Person.prototype.sayHello = function() {
  console.log(`Hello, my name is ${this.name}.`);
};

function Student(name, major) {
  Person.call(this, name);
  this.major = major;
}

Student.prototype = Object.create(Person.prototype);

Student.prototype.constructor = Student;

const student = new Student('John', 'Computer Science');

student.sayHello(); // 输出:Hello, my name is John.
  1. 寄生式继承 :寄生式继承是一种不涉及原型链的继承方式。它允许您通过创建一个新对象并将父类属性和方法复制到该对象中来实现继承。例如:
function Person(name) {
  this.name = name;
}

Person.prototype.sayHello = function() {
  console.log(`Hello, my name is ${this.name}.`);
};

function Student(name, major) {
  const person = new Person(name);

  person.major = major;

  return person;
}

const student = Student('John', 'Computer Science');

student.sayHello(); // 输出:Hello, my name is John.
  1. 类式继承 :类式继承是ES6引入的一种新的继承方式。它允许您使用class来定义类,并通过extends关键字来实现继承。例如:
class Person {
  constructor(name) {
    this.name = name;
  }

  sayHello() {
    console.log(`Hello, my name is ${this.name}.`);
  }
}

class Student extends Person {
  constructor(name, major) {
    super(name);
    this.major = major;
  }
}

const student = new Student('John', 'Computer Science');

student.sayHello(); // 输出:Hello, my name is John.

总结

JavaScript中的继承机制非常灵活,允许您根据自己的需要选择不同的继承方式。原型继承和构造函数继承是最常用的两种继承方式,而组合继承和寄生式继承则更适合特殊场景。类式继承是ES6引入的一种新的继承方式,它提供了更加简洁和易用的语法。