Manishpant
Manishpant

Reputation: 47

Navigating the Prototype chain in javascript

function Student(name, age) {
  this.name = name;
  this.age = age;
}

Student.prototype.showDetails = function () {
  console.log(`${this.name}, ${this.age}`);
};

let Manish = new Student('Manish', 34);
console.log(Manish.__proto__.__proto__.__proto__);
console.log(Manish);

In the above code, the second last line

console.log(Manish.__proto__.__proto__.__proto__);

...logs null as expected. However when I manually navigate through the prototype chain using the object from the last line console.log(Manish), I have to go down 5-6 levels of the __proto__ property till I get a null value.

Is there some explanation for this difference? Image one Image two

Upvotes: 1

Views: 130

Answers (1)

trincot
trincot

Reputation: 350290

The __proto__ entry that you see in the third level in the console, is the getter function which you execute when you do Manish.__proto__. Realise that Manish does not have an own property with the name __proto__, it is by following the prototype chain that it makes access to the __proto__ getter that you see in the console output.

Note also that the console output executes that getter to show you the object which is the same object it shows at the [[Prototype]] entry at the top level.

Key here is that when you access __proto__ like you do, you execute a function (getter) that is defined higher up the prototype chain.

The [[Prototype]] entries are not JavaScript properties, but internal slots which are defined in the ECMA Script specification, but are not accessible as properties in JavaScript code. Console interfaces provide access to these slots to provide additional transparency, but it can also lead to confusion.

Upvotes: 1

Related Questions