javascriptoopprototypeprototypejsprototypal-inheritance

What is the correct way to inherit from a prototype?


I have 2 "classes":

const Person = function(firstName, birthYear){
  this.firstName = firstName;
  this.birthYear = birthYear;
}
Person.prototype.sayHi = function(){
  console.log('Hi!');
}

And

const Student = function(firstName, birthYear, course){
  Person.call(this, firstName, birthYear)
  this.course = course;
};

According to what I've learnt from the course I'm doing, if I want Student to inherit the behaviour of Person I should write this:

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

My question is: what is the difference between this:

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

And this:

Student.prototype = Person.prototype;

Solution

  • One is a duplicate, the other is a pointer. The difference would be felt when you change one of them with or without affecting the other. Specifically, changing the child whose prototype wasn't copied would affect the parent.

    Let's test:

    const Person = function(firstName, birthYear) {
      this.firstName = firstName;
      this.birthYear = birthYear;
    }
    Person.prototype.sayHi = function() {
      console.log('Hi!');
    }
    
    var person = new Person();
    
    const Student1 = function(firstName, birthYear, course) {
      Person.call(this, firstName, birthYear)
      this.course = course;
    };
    
    const Student2 = function(firstName, birthYear, course) {
      Person.call(this, firstName, birthYear)
      this.course = course;
    };
    
    Student1.prototype = Object.create(Person.prototype);
    Student2.prototype = Person.prototype;
    var stud1 = new Student1()
    var stud2 = new Student2()
    
    // now we change person
    Person.prototype.another = function() {
      console.log('Another Hi!');
    }
    Person.prototype.num = 12
    
    // so who's got it?
    stud1.another()
    stud2.another()
    
    // both! because a prototype points to functions
    // but the other way would affect the parent
    Student2.prototype.another = function() {
      console.log("I affected parent - ver 2");
    }
    Student1.prototype.another = function() {
      console.log("I affected parent - ver 1");
    }
    
    console.log (Student2.prototype.another == Student1.prototype.another)  // false
    person.another()