javascriptprototypal-inheritanceprototype-chain

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


I've been learning about prototype in Javascript from a Pluralsight course. And I have some confusion about it.

Here's the example. I have 2 constructors Person and 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;
  };
}

Then create an instance of Student:

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

Now, in the tutorial, it says that in order for michael to inherit everything from Person, there are 2 steps:

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

However, if I remove step 1 and only follow with step 2, the result remains the same. michael is still able to inherit everything from Person. The thing is, what's the point of step 1 anyway? If I remove step 2 and only get along with step 1, michael won't be able to inherit anything from Person.

FYI, here's the course url: https://app.pluralsight.com/course-player?clipId=f1feb535-bbdd-4255-88e3-ed7079f81e4e


Solution

  • This is because your constructors are adding all the properties to this, you're not using the prototypes.

    Normally, methods are added to the prototype, not each instance, e.g.

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

    If you don't create the prototype chain, Student won't inherit a method defined this way.