Welcome to part-3 of the series.
Let’s start from where we left in the earlier part. Consider the below code of using constructor functions in JS. The problem in this is that, whenever we create a new variable with new keyword. The inflateTires function is created for each of them.
The problem with new keyword in constructors
Introduction to Prototype
Consider the below example. In the below example foo have the property which is able to access the its prototype. The properties also known as prototype and it is written as foo.prototype
The prototype example
Let consider the below sample to understand it more better. Whenever a function is created there are two object one is the function object another is the prototype object. Now to access the Prototype object we have a property on the function object also known as “prototype”.
The prototype confusion
calling foo with new keywords
Let’s look in the below diagram, to find what is this weird looking proto property . Actually whenever we call a function with the new keyword a new object is created which have this proto property, and it points to the object of the function. If you call the function again with the new keyword it will again create a similar thing.
The proto property
Let’s see an example to learn the things which you have seen in the diagram. We have created an Empty function foo. Then created a newFooObj using the new keyword on the function. Now using the property prototype created a test variable which contains some string. Now we can access the test variable using the newFooObj object proto property.
foo.prototype === newFooObj.proto
The benefit of Prototype
This concludes the part 3 of the series.