Creating Objects Using Constructor Function

You must be wondering now what is a Constructor Function? Let’s just talk about the constructor first, what is the main purpose of a constructor in a programming language.

A constructor is a function that is used to create an object and initialize the properties. Initializing properties means setting the initial value for all the properties of an object. We talk about constructors when we use classes, as constructors name is same as that of the class. Here we are going to talk about constructor functions which is a slightly different concept from constructors.

Constructor functions are used to create multiple objects of the same object type. They just define the “blueprint” for creating many objects.

Example of a constructor function:

Name:John Miller

In the example above, we created a constructor function Person that takes 3 parameters. On line 12 , the ‘new’ keyword creates an empty Person object like const Person = {} internally and initializes the properties by sending the value of the properties as an argument to the function call. The function Person returns ‘this’ i.e. it returns the newly created object which is stored in variable person1.

The properties for the objects are initialized and now we call the function print() on person1 object. The ‘this’ keyword inside print() function represents the object that is the owner of the print() function, i.e. person1 in this case. Likewise we can create another object of Person type with different values. For example:

console.log("Person1 Information");
const person1 = new Person("John Miller",28,"American");
console.log("Person2 Information");
const person2 = new Person("Amanda Jones",26,"American");
Person1 Information
Name:John miller

Person2 Information
Name:Amanda Jones

In the above example we see that we created two different objects with different values but of the same object type Person. This is the main use case of constructor functions.

You must be wondering what is the difference between a normal function and a constructor function. There are few differences :

  1. Main difference is the creation of multiple objects using Constructor Functions which we cannot achieve through normal functions.
  2. The ‘ new’ keyword – we use the new keyword to create an object.
  3. The naming convention. Normal function follows the camelCase naming convention and the constructor function follows the Pascal naming convention.
  4. The constructor function returns ‘this’ object, whereas inside the normal function you have to explicitly mention the return statement.

This was the basic concept of constructor functions. One should have a knowledge of ‘new’ and ‘this’ keyword to understand this concept better.

Leave a Reply

Your email address will not be published.