当我们在 JS 中已经有了 Object.prototype.use(object) 时,创建原型链有什么意义?

what's the point of creating prototype chain when we've already had Object.prototype.use(object) in JS?

我一直在通过 Pluralsight 课程学习 Javascript 中的原型。我对此有些困惑。

举个例子。我有 2 个构造函数 Person 和 Student:

function Person(firstName, lastName, age) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;

  this.getFullName = function() {
    console.log(this.firstName + this.lastName)
  }
}

function Student(firstName, lastName, age) {
  this._enrolledCourses = [];

  this.enroll = function (courseId) {
    this._enrolledCourses.push(courseId);
  };

  this.getCourses = function () {
    return this._enrolledCourses;
  };
}

然后创建 Student 实例:

let michael = new Student("Michael", "Nguyen", 22);

现在,在教程中,它说为了让 michael 继承 Person 的所有内容,有 2 个步骤:

Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
function Student(firstName, lastName, age) {
  Person.call(this, firstName, lastName, age); <---- this line

  this._enrolledCourses = [];

  this.enroll = function (courseId) {
    this._enrolledCourses.push(courseId);
  };

  this.getCourses = function () {
    f;
    return this._enrolledCourses;
  };
}

但是,如果我删除第 1 步,只执行第 2 步,结果仍然相同。 michael 仍然能够继承 Person 的所有内容。问题是,第一步的意义何在?如果我删除第 2 步而只与第 1 步相处,michael 将无法从 Person.

继承任何内容

仅供参考,这是课程 url:https://app.pluralsight.com/course-player?clipId=f1feb535-bbdd-4255-88e3-ed7079f81e4e

这是因为您的构造函数将所有属性添加到 this,您没有使用原型。

通常情况下,方法会添加到原型中,而不是每个实例中,例如

function Person(firstName, lastName, age) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;
}

Person.prototype.getFullName = function() {
  console.log(this.firstName + this.lastName)
}

如果不创建原型链,Student将不会继承以这种方式定义的方法。