I’ve been learning about JavaScript object inheritance and came across two terms that seem related but are a bit confusing: __proto__
and prototype.
From what I understand: __proto__
is a property found on all objects, and it points to the prototype of the object.
prototype is a property of constructor functions.
However, I’m not quite clear on the practical differences between these two and how they are used differently in JavaScript. Could someone explain the difference between __proto__
and prototype with examples? Specifically, I’m interested in understanding:
How and when to use __proto__
vs prototype.
The role each plays in the prototype chain and inheritance.
Any clarification with code examples would be greatly appreciated!
2
Answers
To access the prototype of an instantiated object you can use
__proto__
.prototype
is used to access the prototype attached to a class.So, accessing
__proto__
on an object is the same as accessingprototype
on its constructor.Usually
prototype
is a property of a function. When you call a function with keywordnew
you create an object with the function called as a constructor and the function’s prototype becomes__proto__
property of the object. So__proto__
is a property of an object that references the function’s propertyprototype
. In reality__proto__
is a getter/setter inObject.prototype
. And it’s deprecated andObject.get/setPrototypeOf()
is now recommended.Due dynamic nature of JS you can assign any object as a prototype.