Prototypes are scary
JavaScript is a prototype based language as we all know. Lets deconstruct the definition of prototypes in JavaScript.
When you start of learning object orientated programing with JavaScript. You will come in contact with prototypes and prototypal inheritance. I will try to make you a little bit more comfortable with this concept.
A Prototype is a member of an object and can define the inheritance of a instance.
Before we create our own prototype. Lets just see a quick example of how we are already dealing with prototypes on daily basis.
Here’s an array
x is an instance of Array. x inherits all prototype properties from Array. So we could for example call Array.prototype.map() function on x
Lets create our own prototype. For this demonstration we will be using the constructor pattern.
Now we want sweden to say hello to the world. This is where prototypes and the prototype-chain comes into play.
createCountry now has a helloWorld prototype property which represents a function.
sweden is still an object with the key value pair of { country: ‘Sweden’ } with a prototypal reference of helloWorld.
The interpreter looks for helloWorld
If no references is found it will start to jump up the prototype chain until the request is satisfied
In this case helloWorld can be related to sweden via the prototype chain.
If we now add a new country
Same goes for canada, it will inherite the protype properties from createCountry. This is how a prototype and the prototype chain works.
The concept of prototypes and prototypal inheritance can be more stretched. I hope you found this article helpful. If you have any ideas or examples please share below!
Enjoy your code.