Welcome to part-3 of the series. You can find the part-2 here.
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.
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
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”.
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.
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.
This concludes the part 3 of the series. You can find the final part here.