Constructor
Introduction
In Javascript, Constructor is used to Create Object. You can create multiple objects by using same constructor.
Declaring Constructor
Syntax
Example
Here,
We have only declared a Constructor that we will use later to create a Object.
Accessing Constructor
Once, We have declared a constructor we need to call or access the constructor
Syntax
Example
Here, We have Created a Constructor with Name identity then, we have created a new Object with name person
In the Console, person.firstName i.e. John will be Printed. , person.lastName i.e. Doe will be printed and person.age i.e. 20 will be printed.
It will also print welcomeMessage i.e. Hello John, it is a object method.
Now, Let me tell you why we should use constructor.
Because Once you have declared a constructor you can Create Multiple Objects.
For Example
Here, we have created 2 objects by using a same constructor.
Constructor With Function Parameters
In the Above Example you must be wondering what is the use of creating a multiple objects for same constructor.
But what if i tell you that you can create number of unique persons by using the Constructor, then it creating multiple users will be boon for us.
Let's me tell you how we can achieve this.
Here,
We have created multiple objects with unique parameter (firstName, lastName and age) by using single Constructor.
Adding Properties and Methods to Object.
Here,
In the constructor we have only declared firstName , lastName , age
Then, we have added gender and welcomeMessage to the Object person
You can add properties to the constructor in the same you add properties to the Objects.
Only properties can be added to the Constructor, if you want to add Methods to the Constructor then it can't be done.