I was learning inheritance and Prototype chaining. I was stuck after seeing this behaviour of resetting the constructor function's prototype inside the function itself. On instantiating
- Case
const Person = function (name,age) {
this.name = name;
this.age = age;
}
Person.prototype.calcAge = function () {
console.log(`My age is ${2022-this.age}`);
}
const Student = function (name,age,course) {
Person.call(this,name,age);
this.course = course;
Student.prototype = null; // This should set Student's Prototype to null and
// thus should not let instance to access intro property.
}
Student.prototype.intro = function () {
console.log(`I am ${this.name} and my course is ${this.course}`)
};
const mike = new Student("mike",2000,"cse");
mike.intro();
In the code above, the output is I am mike and my course is cse but while instantiating I did set Student.prototype = null; so how is mike instance still accessing intro method.
At the moment you call
new, the prototype object is taken fromStudent.prototypeand used to createthis. So at that moment the proto ofthisis the object thatStudent.prototypereferences.It is that proto reference that is later used to find the definition of
intro. It is found viaObject.getPrototypeOf(mike), not viaStudent.prototype. The latter only serves for future constructions.By setting
Student.prototypetonull, you only determine what will happen with the next use ofnew Student. But for the instance that was already created, it comes too late.Object.getPrototypeOf(this)(when in the constructor's execution), will still refer to the original prototype object.Here some extra
console.logto illustrate that point: