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', '', 29);
var user2 = new User('John', 'Cena', '', 45);
var user3 = new User('Tony', 'Stark', '', 52);

User {firstName: "Ramesh", lastName: "Fadatare", emailId: "", age: 29}
User {firstName: "John", lastName: "Cena", emailId: "", age: 45}
User {firstName: "Tony", lastName: "Stark", emailId: "", age: 52}