Prototypes in JavaScript
Table of contents
No headings in the article.
The word 'prototype' according to Google is "an original model on which something is patterned". Does this hold in the case of Javascript?
This article assumes that you have spent significant time with Javascript. Hopefully till the basics of classes and OOP in Javascript.
A 'prototype' can also be called a model or a blueprint. In the case of Javascript, these synonyms do hold meaning. If you come from C++ or Java then the idea of classes is pretty self-explanatory, a datatype that contains properties and methods and will be allocated memory once instantiated. This phrase holds even in the case of Javascript.
But JavaScript has another unique way of defining and storing classes and objects.
Let's look at some JS syntax that might look weird to people with C++ or Java backgrounds.
If you are from a C++ / Java background. There are many surprises in the above code. First of all, the use of 'this' keyword in a normal function outside of class. What do you think would be the output of this code? Undefined? Empty object?
Well, it turned out to be quite absurd. If you observe the code, the contents of the function 'Product' look very similar to that of a constructor in JS. What is JS doing behind the curtains? It is defining a property called 'prototype'.
Let's try to see what JS is doing in the background.
This is the result when you write the same code that we saw before in any browser's developer console. Notice the '<prototype>' property at the very end of the snippet. If we go ahead and expand that property, we see something like this.
So the entire object that we got looks like this. It has the properties that we had declared in the 'Product' function as well as a property called '<prototype>' and one called 'constructor' which holds a reference to the function 'Product'.
Let's try to visualize what JS is doing.
This is how JS is internally using prototypes to map functions to objects. You might say, "What is the other <prototype> inside the property that we expanded?". That is the topic for my next article.
Please let me know if you liked the article or learned something new.
Also, if some portion of the article needed more clarity or some prerequisite that was not mentioned, feel free to drop your feedback in the comments below.