Search code examples
javascriptinheritanceprototypeprototypal

Javascript - Object.create: Is my understanding correct?


I am trying to understand fully how prototypes work.

This is my definition of a prototype:

A built in property that all objects have (except the Base Object) which points to and references a 'proto{}' object which is a copy of another object whose properties and methods can then be referenced if not found in the original object.

Is that correct? Especially I'm wondering about the 'is a copy of another object' part - meaning that the JS Engine creates a stored copy of Object B in memory space which the prototype property of Object A points to for reference.

Now my questions about Object.create:

My understanding is that this method makes the prototype (or the object itself?) of whatever object it is used on, inherit (IOW, reference a copy of the passed in Object) the properties and methods of another object that is passed in.

var john = Object.create(Person);

In the above code, the john object is created and it's prototype property points to a created object that has the methods and properties of the Person object? Or to put it differently, Object.create makes a copy of the Person object and puts it in a memory space that the prototype property of john points to. Is this a correct understanding of what's going on?

If so, is the reason that a copy of the object ('person') is made, that the prototype of john points to, because that allows the values of the properties and methods to be modified without overwriting the props/methods in the Person object that the prototype object associated with john inherited?

I am trying to break this down so I can understand and trying not to over-complicate the concept.

Here is a picture I drew to further illustrate my current understanding:

enter image description here


Solution

  • No, there is no copying of anything involved. Just strike that part:

    Prototype: A built in property that all objects have (except the Base Object) which points to and references a 'proto{}' object which is a copy of another object whose properties and methods can then be referenced if not found in the original object.

    Keep it simple.

    And yes, because there is a direct reference and nothing else involved, this means that any changes to the inherited properties of the prototype object will dynamically reflect in the object.