Memo to self - Javascript prototypes
A function’s prototype is the object instance that will become the prototype for all objects created using this function as a constructor
An object’s prototype is the object instance from which the object is inherited.
A prototype is not like a class, it is an object.
When a function is created, a prototype object is created and attached to it behind the scenes. If the function is then used as a constructor with the new
keyword, the object that is created has a __proto__
property that is pointing to the same object that is the function’s prototype.
To illustrate:
fluffy.__proto__
is pointing to the same instance as Cat.prototype
. To continue:
This also affects any new instance created:
Due to the way javascript works, we can also access these new properties as though they are on the object itself.
This is a bit weird, especially when you consider the following.
In Javascript, when you check the value of a property on an instance, if the instance does not have the property on it, we go up the chain and the prototype checked for the property. This search goes up the prototypes until either the property is found, or the end of the chain is reached.
fluffy has the property "Purr"
, so the lookup stops early and we don’t get the default greeting of "hi!"
.
You can change the prototype object on the constructor, although it can give some weird side effects:
The existing fluffy and muffin objects still have prototypes pointing to the original function prototype instance. This emphasises the prototypes are all instances of objects living in memory.
Down the rabbit hole.
What we haven’t seen yet is that the Cat prototype also has a prototype.
By default, all objects in Javascript inherit from Object, and Object’s prototype is null.
Inheritance
Why use Object.create
? Object.create
sets up the prototype chain and assigns Animal.prototype as the prototype for Cat.
Alternative syntax:
There are some differences between these, the most important being that the speak
function is no longer enumerable.