返回

简析 JavaScript 中继承的实现方式,助你轻松理解原型链、构造函数和实例继承

前端

在计算机科学中,继承是一种重要的编程概念,它允许一个对象从另一个对象中获取属性和方法。在 JavaScript 中,实现继承的方法有多种,每种方法都有其自身的优点和缺点。本文将分别介绍原型链继承、构造函数继承和实例继承这三种方式,并帮助你理解它们的核心思想和实际运用。

  1. 原型链继承

原型链继承是 JavaScript 中最常见的一种继承方式。它通过设置对象的原型属性来实现继承。每个对象都有一个原型对象,而原型对象又可以有自己的原型对象,如此依次类推,形成一条原型链。当一个对象访问一个不存在的属性或方法时,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

在上面的例子中,Student 对象继承了 Person 对象的属性和方法。当 student.sayHello() 被调用时,JavaScript 会沿着原型链向上查找,找到 Person.prototype.sayHello() 方法并执行它。

  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;
}

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

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

在上面的例子中,Student 对象继承了 Person 对象的属性和方法。当 new Student("John", "Computer Science") 被调用时,首先会调用 Person.call(this, "John"),以便对 student 对象进行初始化。然后,student 对象的 major 属性被设置为 "Computer Science"。

  1. 实例继承

实例继承是通过直接将父类的实例赋值给子类的实例来实现继承。这种方式比较简单,但它也有一个缺点,就是子类的实例无法访问父类的私有属性和方法。

function Person(name) {
  this.name = name;
  this.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

在上面的例子中,Student 对象继承了 Person 对象的属性和方法。当 new Student("John", "Computer Science") 被调用时,首先会创建一个新的 Person 对象,然后将这个 Person 对象赋值给 student 对象。最后,student 对象的 major 属性被设置为 "Computer Science"。

总之,原型链继承、构造函数继承和实例继承是 JavaScript 中实现继承的三种主要方式。每种方式都有其自身的优点和缺点,在实际开发中需要根据具体情况选择合适的方式。