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.
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.
- It will create a new empty object.
- 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.
- function myConstructorFucn() {
- }
- myConstructorFucn.prototype.age = 25;
- var consFunc = new myConstructorFucn()
- console.log(typeof consFunc)
- console.log(consFunc);
From the above figure, you can notice the empty object linked to the object _proto_ and the age property is set to it.
- It will bind the property declared with this keyword to the new object.
- function myConstructorFucn() {
- this.name = "David";
- }
- myConstructorFucn.prototype.age = 25;
- var consFunc = new myConstructorFucn()
- console.log(typeof consFunc)
- console.log(consFunc);
From the above figure, you can notice the property name is bound with the object by using the "this" keyword in the context.
- If the called functions don’t have return value, it will return an empty object by default.
- function myConstructorFucn() {
- }
- myConstructorFucn.prototype.y = 25;
- var consFunc = new myConstructorFucn()
- console.log(typeof consFunc)
- 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.