简体   繁体   中英

How does the prototype object of an inherited class equal a new instance of the original class in JavaScript?

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!

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.

问题的方法 示例的方法

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM