Different ways to create an object.

There are many ways to create an object in javascript as below:
Object Constructor
The simplest ways to create an empty object using the object constructor.
var object = new Object();
Note: Currently, this method is not recommended.
Object Create method
The create method of ‘Object’, creates a new object as a parameter.
var object = Object.create(null);
Object literal method
The object literal syntax is equivalent to create method when it passes null as parameter.
var object = {};
Function Constructor
Create any function and apply the new operator to create a new object instance.
function Person(name){
var object = {};
object.name = name;
object.age = 22;
return object;
}
var object = new Person("Sagar");
Function Constructor with prototype:
This is similar to function constructor but it uses prototype for their properties and methods,
function Person(){};
Person.prototype.name = "Sagar";
var object = new Person();
This is equivalent to an instance created with an object create method with a function prototype and then call that function prototype and then call that function with an instance & parameters as argument.
function func{}
new func(x,y, z);
OR
function func{}
// create a new instance using function prototype
var newInstance = Object.create(func.prototype)
// Call the function
var result = func.call(newInstance,x,y,z);
// If the result is a non-null object then use it otherwise just use the new instance
console.log(result && typeof result === "object"? result : new Instance)
ES6 Class Syntax
ES6 introduces class feature to create the object.
class Person{
constructor(name){
this.name = name;
}
}
var object = new Person("Sagar")
Singleton Pattern:
A Singleton is an object which can only be instantiated one time reapeated calls to its constructor return the same instance and this way one can ensure that they don’t accidentally create multiple instances.
var object = new function (){
this.name = "Sagar";
}
Subscribe to my newsletter
Read articles from Sagar Kumar Jha directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Sagar Kumar Jha
Sagar Kumar Jha
Softwares are art and I am an artist