There are various ways to creae an object in JavaScript.
It is the simplest way to create an object just by using object literal notation `{}`.
// object notation-{}
let person = {
name: "Wasif",
age: 23,
city: "India"
};
We can create an object through the object constructor.
// object constructor
let person = new Object();
person.name = "Wasif";
person.age = 23;
person.city = "India";
We also create a object by using function Constructor.
// function constructor
function Person(name, age, city) {
this.name = name;
this.age = age;
this.city = city;
}
let person1 = new Person("Wasif", 23, "India");
let person2 = new Person("Rohit", 25, "German");
Now JavaScript also supports class bases syntax for creating object.
// ES6 classes
class Person {
constructor(name, age, city) {
this.name = name;
this.age = age;
this.city = city;
}
}
let person1 = new Person("Wasif", 23, "India");
let person2 = new Person("Rohit", 25, "German");