I was going through Mozilla explanation of prototype inheritance https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain. Thought of trying some exmple in chrome console.
function f() {
this.a =1;
this.b =2;
}
let o = new f();
f.prototype.b =3;
f.prototype.c =4;
I noticed that prototype of the function f() has a constructor and that again has a prototype and it keep going on like below: f.prototype.constructor.prototype.constructor.prototype.constructor.prototype.constructor.prototype.constructor
Now according to the mozilla documentation "Each object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. By definition, null has no prototype, and acts as the final link in this prototype chain"
I am sure I am looking it from a wrong angle. Can someone put some perspective here. What actually is going on ? why do we have an unending constructor and prototype chain ?
You have a circular reference. Given a function, you can access the prototype
property of it to get to the object that will be the internal prototype of any instances.
function f() {
this.a =1;
this.b =2;
}
let o = new f();
console.log(f.prototype === Object.getPrototypeOf(o));
On this .prototype
object, you can access its constructor
property to get back to the associated function.
The .prototype
of a function and .constructor
of that prototype are links to each other. Given either, you can access the other.
The actual prototype chain for f
is:
f <- Function.prototype <- Object.prototype
The prototype chain for o
is:
o <- f.prototype <- Object.prototype
Note that the .prototype
property does not reference the object that's the internal prototype of the one you're calling it on. To get to the internal prototype of some object obj
, you have to use Object.getPrototypeOf
(or __proto__
, which is deprecated). The .prototype
property is a special property of functions which will refer to the internal prototype of any instances of that function which may get created. Eg const instance = new SomeClass()
will result in instance
having an internal prototype of SomeClass.prototype
.