I've been struggling to wrap my head around how exactly prototype inheritance vs setting a method on each new object instantiated using the constructor saves memory. The __proto__
points at the prototype of the parent constructor but from reading MDN it seems that all of the methods on the prototype of a parent are copied into the __proto__
object. So how is that different from directly creating key value pairs on an instantiated object?
The methods on the parent's prototype are not copied onto __proto__
. The __proto__
property is just a reference to it. You can prove that using JavaScript's strict equality comparison operator:
child.__proto__ === parent.prototype // true
They are the exact same object, not a copy of an original. If this information surprises you, consider that objects in JavaScript are stored by reference. So if you have an object like this:
const obj = {
prop: 'value'
};
And you assign this object to another variable:
const obj2 = obj;
There are not two separate objects, rather there are two variables each having a reference to the same object. The references do not take up the space of the object, they are just memory pointers. To put it another way, the object exists once and there are two variables with references to it.