Constructor function is used to create the Object through new keyword.
First character of the constructor function should be in Capital letters.
Syntax:-
function FunctionName(){
// logic implement
}
var obj = new FunctionName();
Example:- Suppose, You have to create Employee() constructor function.
function Employee(){
this.firstName="John";
this.lastName="Mathew";
this.email="john@abc.com";
}
// Now, create the Object
var emp= new Employee();
console.log(emp.firstName);
console.log(emp.lastName);
console.log(emp.email);
Mathew
john@abc.com
Note:- this property reference to the constructor function.
Adding Method in Constructor function
Now you want to add method fullName() in the constructor function.
function Employee(){
this.firstName="John";
this.lastName="Mathew";
this.fullName= function(){
return this.firstName+" "+this.lastName;
}
}
Now, create the object
var emp = new Employee();
console.log(emp.fullName())
Parameters pass in the constructor function
You can pass multiple parameters in the function according your requirements.
Syntax:-
function FunctionName(parameter_1, parameter_2,....parameter_n){
// logic implement
}
var obj = new FunctionName(parameter_1, parameter_2,....parameter_n);
Example:-
function Employee(first_name, last_name){
this.full_name="Welcome "+first_name+" "+last_name;
}
// Now, create the Object
var emp= new Employee("John","Mathew");
console.log(emp.full_name);
You can create multiple objects based on your requirements.
var emp= new Employee("Rom","Taylor");
console.log(emp.full_name);
Adding property into the constructor function object
function Employee(first_name, last_name){
this.firstName=first_name;
this.lastName=last_name;
this.fullName= function(){
return this.firstName+" "+this.lastName;
}
}
Suppose, you have to add new property department in the constructor function employee.
var emp = new Employee("John","Mathew");
emp.department="Sales";
console.log(emp.department)
Now, you create another object and call the department property then it will show undefined.
var emp2 = new Employee("Rom","Taylor");
console.log(emp2.department)
Note:- If you add property after created the object then it will work for same object not other object.