Aryan PrajapatKnowledge Contributor
What are the possible ways to create objects in JavaScript
What are the possible ways to create objects in JavaScript
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Questions | Answers | Discussions | Knowledge sharing | Communities & more.
There are many ways to create objects in javascript as mentioned below:
Object literal syntax:
The object literal syntax (or object initializer), is a comma-separated set of name-value pairs wrapped in curly braces.
var object = {
name: “Sudheer”,
age: 34
};
Object literal property values can be of any data type, including array, function, and nested object.
Note: This is one of the easiest ways to create an object.
Object constructor:
The simplest way to create an empty object is using the Object constructor. Currently this approach is not recommended.
var object = new Object();
The Object() is a built-in constructor function so “new” keyword is not required. The above code snippet can be re-written as:
var object = Object();
Object’s create method:
The create method of Object is used to create a new object by passing the specified prototype object and properties as arguments, i.e., this pattern is helpful to create new objects based on existing objects. The second argument is optional and it is used to create properties on a newly created object.
The following code creates a new empty object whose prototype is null.
var object = Object.create(null);
The following example creates an object along with additional new properties.
let vehicle = {
wheels: ‘4’,
fuelType: ‘Gasoline’,
color: ‘Green’
}
let carProps = {
type: {
value: ‘Volkswagen’
},
model: {
value: ‘Golf’
}
}
var car = Object.create(vehicle, carProps);
console.log(car);
Function constructor:
In this approach, create any function and apply the new operator to create object instances.
function Person(name) {
this.name = name;
this.age = 21;
}
var object = new Person(“Sudheer”);
Function constructor with prototype:
This is similar to function constructor but it uses prototype for their properties and methods,
function Person() {}
Person.prototype.name = “Sudheer”;
var object = new Person();