Just think of constructor functions as classes and the properties of the prototype (ie of the object referenced by the constructor function's prototype property) as shared members, ie members which are the same for each instance. In class-based systems, methods are implemented the same way for each instance, so methods are normally added to the prototype, whereas an object's fields are instance-specific and therefore added to the object itself during construction.
Consider the following keyValueStore object :
We can create a new instance of this object by doing this :
Each instance of this object would have the following public properties :
Now, suppose we create 100 instances of this keyValueStore object. Even though get, set, delete, getLength will do the exact same thing for each of these 100 instances, every instance has its own copy of this function. Now, imagine if we could have just a single get, set, delete and getLength copy, and each instance would reference that same function. This would be better for performance and require less memory. That's where prototypes come in. A prototype is a "blueprint" of properties that is inherited but not copied by instances. So this means that it exists only once in memory for all instances of an object and is shared by all of those instances. Now, consider the keyValueStore object again. We could rewrite it like this :
This does EXACTLY the same as the previous version of the keyValueStore object, except that all of its methods are now put in a prototype. What this means, is that all of the 100 instances now share these four methods instead of each having their own copy.
When a constructor creates an object, that object implicitly references the constructor’s “prototype” property for the purpose of resolving property references. The constructor’s “prototype” property can be referenced by the program expression constructor.prototype, and properties added to an object’s prototype are shared, through inheritance, by all objects sharing the prototype.
The interface to standard classes become extensible. For example, we are using the Array class and we also need to add a custom serializer for all our array objects. Would we spend time coding up a subclass, or use composition or ... The prototype property solves this by letting the users control the exact set of members/methods available to a class. Think of prototypes as an extra vtable-pointer. When some members are missing from the original class, the prototype is looked up at runtime.
Every object has an internal property, [[Prototype]], linking it to another object:
object [[Prototype]] -> anotherObject
Some environments expose that property as __proto__:
anObject.__proto__ === anotherObject
We create the [[Prototype]] link when creating an object:
and we create the [[Prototype]] link with new:
So these statements are equivalent: