Skip to content Skip to sidebar Skip to footer

Why My __proto__ Reference Shows Wrong Name In Console?

My proto reference of 'mike' instance points to 'Student' but as its name shows 'Person' , I don't know why is that. Here is my code and screenshot of console below: When I check

Solution 1:

Student.prototype = Object.create(Person.prototype) In this case, you are creating a new object and make it the value of Student.prototype. The new object Student has Person.prototype as its prototype.


Solution 2:

The very first thing you see in Chrome's console is Student. That is the "type" of your mike object.

On the other hand, the __proto__ property of mike references the prototype from which this instance was created. Your code has explicitly defined that prototype with the following statement:

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

So, from that moment on, Student.prototype instanceof Person is true, but Student.prototype instanceof Student false. And all instances created with new Student, will reference the Student.prototype in their __proto__ property. So what you see is as expected.

The fact that the following assignment was made, doesn't change this behaviour:

Student.prototype.constructor = Student;

This is a cosmetic change, and doesn't determine the nature of the instances that Student creates. That might have mislead you.

class syntax

The code you provided performs the steps needed to set up a prototype chain, where a Student inherits from a Person.

In modern JavaScript it is much less cryptical to make this happen. Nowadays you would write this example as follows:

class Person {
    constructor(firstName,birthYear) {
        this.firstName = firstName;
        this.birthYear = birthYear;
    }
    calcAge() {
        console.log(2037 - this.birthYear);
    }
}

class Student extends Person {
    constructor(firstName, birthYear, course) {
        super(birthYear, course);
        this.course = course;
    }
    introduce() {
         console.log(`My name is ${this.firstName} and ,I study ${this.course}`);
    }
}

const mike = new Student('Mike',2020, 'Computer Science');

console.log(mike);

The result in the console will also here confirm that the prototype object of a Student instance is an instance of Person (not of Student).


Post a Comment for "Why My __proto__ Reference Shows Wrong Name In Console?"