Constructor Function In JavaScript

From this blog, you will learn how to create a constructor function in JavaScript.

Introduction 

In many other programming languages, the "new" keyword is used to initialize a class; however, in the case of JavaScript, "new" is used to create an object. We can create an object of the function also which is called a Constructor Function.

Constructor Function


The function call becomes a constructor call when the "new" keyword is used in it. It is just a modification made in a function. 
 
By adding the "new" keyword in the function call, it performs the following actions. 
  1. It will create a new empty object.
  2. It will link the new empty object to another object, which means it will set a new object ‘_proto_’ to the constructor function which can be accessed through prototype property.
    1. function myConstructorFucn() {    
    2.         }    
    3.         myConstructorFucn.prototype.age = 25;    
    4.         var consFunc = new myConstructorFucn()    
    5.         console.log(typeof consFunc)    
    6.         console.log(consFunc);    
    Constructor Function In JavaScript
    From the above figure, you can notice the empty object linked to the object _proto_ and the age property is set to it.

  3. It will bind the property declared with this keyword to the new object. 
    1. function myConstructorFucn() {    
    2.             this.name = "David";               
    3.         }    
    4.         myConstructorFucn.prototype.age = 25;    
    5.         var consFunc = new myConstructorFucn()    
    6.         console.log(typeof consFunc)    
    7.         console.log(consFunc);    
    Constructor Function In JavaScript
    From the above figure, you can notice the property name is bound with the object by using the "this" keyword in the context.

  4. If the called functions don’t have return value, it will return an empty object by default.
    1. function myConstructorFucn() {    
    2.                     }    
    3.         myConstructorFucn.prototype.y = 25;    
    4.         var consFunc = new myConstructorFucn()    
    5.         console.log(typeof consFunc)    
    6.         console.log(consFunc);    
    From the above code, you can notice there is no return statement in myConstructorFunc but still, it will return an empty object. 
Constructor Function In JavaScript 

Conclusion

 
From this blog, we have seen the impact of the "new" keyword in the function call. Also, we saw how to create a constructor function and the actions involved in creating a constructor function.