Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance within Javascript

I'm studying the concept of inheritance in Javascript, and the tutorial I'm looking at uses this code:

// define the Student class
function Student() {
  // Call the parent constructor
  Person.call(this);
}

// inherit Person
Student.prototype = new Person();

// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;

My question is, why is it necessary to both call the parent constructor, Person.call(this), and set the Student prototype equal to a new Person object (i.e. Student.prototype = new Person();)?

like image 908
voltair Avatar asked Apr 05 '13 21:04

voltair


1 Answers

There are two separate issues to deal with.

The first is to make sure new Student objects inherit from Person objects. That's why you do Student.prototype = new Person(). That makes the Student.prototype a Person so Student objects will inherit whatever that object inherits (from Person.prototype).

The second is to apply any behavior in the Person constructor to any new Student objects. That's why you do Person.call(this). This is technically not needed if the Person constructor doesn't have any code that modifies the new object, but it's still a good idea to do it just in case you add some code to Person later.


Side note, when setting up the inheritance, it's better to do:

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

...and shim Object.create if needed. This way you don't actually need to invoke the Person constructor in order to get a new object that inherits from Person.prototype. Again, sometimes not an issue, but sometimes there are side effects in the constructor that are undesired when setting up the inheritance.

like image 89
user1106925 Avatar answered Sep 22 '22 03:09

user1106925