返回

**四种常见的 JS 继承类型及其应用场景**

前端

引言

在 JavaScript 中,继承是一种创建新对象的一种重要机制,它允许新对象从现有对象继承属性和方法。这篇文章介绍了四种常见的 JS 继承类型:原型链继承、构造函数继承、组合继承和寄生组合式继承。文章还讨论了每种继承类型的优缺点,以及它们在实际开发中的应用场景。

原型链继承

原型链继承是最简单的一种继承方式,它通过修改原型对象来实现继承。原型对象是一个特殊的对象,它包含了所有实例对象的公共属性和方法。当一个对象被创建时,它会自动获得一个指向原型对象的指针,这个指针被称为原型链。

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

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

const person = new Person('John');

person.sayHello(); // Hello, my name is John!

在上面的示例中,Person 函数是构造函数,它用于创建一个新的 Person 对象。当 person 对象被创建时,它会自动获得一个指向 Person.prototype 对象的指针。这个指针被称为原型链。person 对象可以通过原型链访问 Person.prototype 对象的属性和方法。

构造函数继承

构造函数继承是另一种常见的继承方式,它通过调用父构造函数来实现继承。在构造函数继承中,子构造函数会继承父构造函数的所有属性和方法。

function Person(name) {
  this.name = 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!
console.log(student.major); // Computer Science

在上面的示例中,Student 函数是构造函数,它用于创建一个新的 Student 对象。Student 构造函数通过调用 Person 构造函数来实现继承。这使得 Student 对象可以继承 Person 对象的所有属性和方法。

组合继承

组合继承是原型链继承和构造函数继承的结合,它通过组合这两种继承方式来实现继承。在组合继承中,子构造函数会先调用父构造函数,然后将父构造函数的原型对象作为子构造函数的原型对象。

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!
console.log(student.major); // Computer Science

在上面的示例中,Student 函数是构造函数,它用于创建一个新的 Student 对象。Student 构造函数通过调用 Person 构造函数来实现继承。这使得 Student 对象可以继承 Person 对象的所有属性和方法。然后,Student.prototype 被设置为 Object.create(Person.prototype),这使得 Student 对象可以访问 Person.prototype 对象的属性和方法。最后,Student.prototype.constructor 被设置为 Student,这使得 Student 对象的 constructor 属性指向 Student 构造函数。

寄生组合式继承

寄生组合式继承是组合继承的变体,它通过创建一个新的对象来实现继承,这个新的对象包含了父对象的所有属性和方法。在寄生组合式继承中,子构造函数不会调用父构造函数,而是通过复制父对象的属性和方法来实现继承。

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 = new Student('John', 'Computer Science');

student.sayHello(); // Hello, my name is John!
console.log(student.major); // Computer Science

在上面的示例中,Student 函数是构造函数,它用于创建一个新的 Student 对象。Student 构造函数通过创建一个新的 Person 对象来实现继承,这个新的 Person 对象包含了 Person 对象的所有属性和方法。然后,Student 构造函数将 major 属性添加到 Person 对象上。最后,Student 构造函数返回 Person 对象。

总结

原型链继承、构造函数继承、组合继承和寄生组合式继承是 JavaScript 中最常见的四种继承类型。每种继承类型都有其优点和缺点,在实际开发中应根据具体情况选择合适的继承类型。