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();
)?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With