javascriptprototype-chain

Why there is a need to use Object.create() in prototype interitance


I was looking at an inheritance example using prototypes as below:

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

function Student(name){
  Person.call(this, name)
}
Student.prototype = Object.create(Person.prototype)
Student.prototype.constructor = Student

let jim = new Student("Jim")

My question is, why there is a need to set the prototype using Object.create(Person.prototype) Why not simply setting it like Person.prototype?


Solution

  • If you do

    Student.prototype = Person.prototype;
    

    and next move try to extend it:

    Student.prototype.a = function(....
    

    You will be affecting Person.prototype as well(since it's strictly the same exact object after assignment)