2

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?

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

That makes sense, thank you. I'd choose this as accepted answer but not enough rep.
You're welcome, no worries. Upvote if you can/want, if not have a good day :)
@ZacharySpringer: You always have enough rep to choose an accepted answer, it’s upvotes that have a requirement :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.