Vahid
Vahid

Reputation: 1957

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?

Upvotes: 3

Views: 67

Answers (1)

skyboyer
skyboyer

Reputation: 23763

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)

Upvotes: 2

Related Questions