Search code examples
javascriptoopobjectprototypeprototypal-inheritance

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:

const Person = function (firstName,birthYear) {
   this.firstName = firstName;
   this.birthYear = birthYear;
}

Person.prototype.calcAge = function () {
   console.log(2037 - this.birthYear);
}


const Student = function (firstName, birthYear, course){
   Person.call(this,firstName,birthYear);
   this.course = course;
};


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

Student.prototype.constructor = Student;

Student.prototype.introduce = function () {
   console.log(`My name is ${this.firstName} and ,I study ${this.course}`);
}

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

console.log(mike);

When I check on console it shows Person:

Console Screenshot


Solution

  • 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.