Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading