I have been learning about inheritance in JavaScript, and could not understand a line of code in the tutorial at https://www.tutorialsteacher.com/javascript/inheritance-in-javascript.
The code is as follows:
function Person(firstName, lastName) {
this.FirstName = firstName || "unknown";
this.LastName = lastName || "unknown";
}
Person.prototype.getFullName = function () {
return this.FirstName + " " + this.LastName;
}
function Student(firstName, lastName, schoolName, grade)
{
Person.call(this, firstName, lastName);
this.SchoolName = schoolName || "unknown";
this.Grade = grade || 0;
}
//Student.prototype = Person.prototype;
Student.prototype = new Person();
Student.prototype.constructor = Student;
var std = new Student("James","Bond", "XYZ", 10);
alert(std.getFullName()); // James Bond
alert(std instanceof Student); // true
alert(std instanceof Person); // true
The part I do not understand is the line right after the commented line, which is:
Student.prototype = new Person();
To my understanding, when an object instance is created, its __proto__
property points to the class's prototype object.
Following this logic, shouldn't the code be:
Student.prototype = new Person().__proto__;
?
I would really appreciate some clarification!
When it comes to inheritance, JavaScript only has one construct: objects. Each object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype.
Every object in JavaScript has a built-in property, which is called its prototype. The prototype is itself an object, so the prototype will have its own prototype, making what's called a prototype chain. The chain ends when we reach a prototype that has null for its own prototype.
The object from where the properties are inherited is called the prototype. In short, objects can inherit properties from other objects — the prototypes.
The most important difference between class- and prototype-based inheritance is that a class defines a type which can be instantiated at runtime, whereas a prototype is itself an object instance.
There's a functional difference. Your way assigns Student's prototype as a reference to Person's. Mutations to either prototype will occur in both. In contrast, when you assign as in the example, you're passing a new Object
with a (deep) copy of Person's prototype. Have a look at the following screenshots.
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