1.

What are constructor functions in JavaScript?

Answer»

In JavaScript everything is an Object. So whenever we create an FUNCTION, there is a one object which is created for that function. But actually there is another object which is created which is known as the Prototype object.
Now to access the Prototype object we have a reference on the function object also known as prototype. Notice the small “p”.

When we create an instance of the function with the NEW keyword interesting THINGS happens. It create something known as __proto__. This is created by the JavaScript engine for every function call using the new keyword.

Now, let’s LOOK how to create an function using prototype and the benefit of it. The below code have two function haveFun and drinkBreak. The function haveFun is an normal function inside the Constructor function. The function drinkBreak is created outside and added to the Prototype Object using it’s reference prototype.

Both the function seems to be doing the same thing, then what’s the benefit.
The benefit of declaring function using prototype is that it’s created once in the Prototype object. So, now whenever we create a new instance of the Constructor function the function is not created again. As in the below screenshot, you can see that emp1 and emp2 both have name and haveFun. But the drinkBreak is inside the __proto__, which is a reference to Prototype object.



Discussion

No Comment Found