Creating Objects – Function Constructor

In this blog we will have a detailed look at how to create objects using Function constructor.

Function constructor is just a blueprint from which instances are created.

In the previous blog we have seen how we created john object.

Let’s assume we have to create multiple objects with same properties as available in the john object. Therefore, we need a blueprint from which we can create these instances. Let’s create a function constructor.

How this works ?

Before looking into the working of the function constructor, we should understand the importance of the new keyword.

When we use the new keyword a brand new empty object is created. Post that, then the function constructor(in this case Person), is called with the arguments which we have specified. Then the this keyword will point to the empty object created by the new keyword, rather than the global object.

Adding inheritance to the Game

Let’s say we want to add calculateAge() method to our objects. We can do that by adding that to our function constructor. All the objects created from the function constructor would reflect this newly added method.

Creating few more objects

We can see that all the newly created objects have calculateAge() attached to it, as it is available in the function constructor. This is just a single function in this case. But let’s assume we have 50 function, with every function having 100 – 200 lines of code. That will not be very efficient, as we will have 3 copies of exact same thing. That is where inheritance comes into play.

As per the last blog, we need to add all the method/properties to the function prototype property. Let’s do this.

None of the object has calculateAge() method attached to it. But still we can access the calculate age method, as it is available in its prototype. Let’s see this.

Inheritance actually works in Javascript.

Inspecting Objects in Console

Let’s see how we can deal with objects in the console. Rather than writing, let’s jump into some action and do stuff.

Let’s expand __proto__:Object

This is a prototype property of the Object object(function constructor) about which we have discussed in the previous blog. This console gives us a visual representation of Prototype chain.

Few more uses of console:

About the author

Deepak Sood

Deepak Sood is Lead Consultant in an IT firm holding expertise in Devops and QA Architecture with 8 years of experience.

His expertise is in building highly scalable frameworks. His skills include Java, Configuration Management, Containers, and Kubernetes.

Reach out to him using contact form.

View all posts