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.
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', '[email protected]', 29);
var user2 = new User('John', 'Cena', '[email protected]', 45);
var user3 = new User('Tony', 'Stark', '[email protected]', 52);
console.log(user1);
console.log(user2);
console.log(user3);
Output:
User {firstName: "Ramesh", lastName: "Fadatare", emailId: "[email protected]", age: 29}
User {firstName: "John", lastName: "Cena", emailId: "[email protected]", age: 45}
User {firstName: "Tony", lastName: "Stark", emailId: "[email protected]", age: 52}
Comments
Post a Comment