6

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!

Boann
  • 48,794
  • 16
  • 117
  • 146
Joon K
  • 161
  • 1
  • 9
  • 1
    its should not be written like this `Student.prototype = new Person().__proto__;`, you can but its discouraged to be implemented that way, and one more thing __proto__ is deprecated as per [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto) also check this [SO question](https://stackoverflow.com/questions/650764/how-does-proto-differ-from-constructor-prototype) – ROOT Jun 07 '20 at 05:44

1 Answers1

2

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.

Question's method Example's method