Create JavaScript Object using Constructor Function

This javascript example shows how to create a JavaScript object using a constructor function. If you call a function using a new operator, the function acts as a constructor and returns an object.

Create JavaScript Object using Constructor Function

Below two steps define and create an object:
  • Define the object type by writing a constructor function. There is a strong convention, with good reason, to use a capital initial letter.
  • Create an instance of the object with a new keyword.
// using constructor function
function User(firstName, lastName, emailId, age){
    this.firstName = firstName;
    this.lastName = lastName;
    this.emailId = emailId;
    this.age = age;
}

var user1 = new User('Ramesh', 'Fadatare', 'ramesh24@gmail.com', 29);
var user2 = new User('John', 'Cena', 'john@gmail.com', 45);
var user3 = new User('Tony', 'Stark', 'tony@gmail.com', 52);

console.log(user1);
console.log(user2);
console.log(user3);
Output:
User {firstName: "Ramesh", lastName: "Fadatare", emailId: "ramesh24@gmail.com", age: 29}
User {firstName: "John", lastName: "Cena", emailId: "john@gmail.com", age: 45}
User {firstName: "Tony", lastName: "Stark", emailId: "tony@gmail.com", age: 52}


Comments