DEV Community

Poopcoder
Poopcoder

Posted on • Originally published at poopcode.com on

What are the possible ways to create objects in JavaScript?

There are many ways to create objects in JavaScript as described below.

Object constructor

The simplest way to create an empty object is using the Object constructor. This approach is not recommended anymore.

var object = new Object();
Enter fullscreen mode Exit fullscreen mode

Object’s create method

The create method of Object creates a new object by passing the prototype object as a parameter to the create() method.

var object = Object.create(null);
Enter fullscreen mode Exit fullscreen mode

Object literal syntax

The object literal syntax is equivalent to create method when it passes null as parameter.

var object = {};
Enter fullscreen mode Exit fullscreen mode

Function constructor

Create any function and apply the new operator to create object instances.

function Employee(name){
   var object = {};
   object.name=name;
   object.salary=1000;
   return object;
}
var object = new Person("John");
Enter fullscreen mode Exit fullscreen mode

Object literal syntax

The object literal syntax is equivalent to create method when it passes null as parameter.

var object = {};
Enter fullscreen mode Exit fullscreen mode

Function constructor + prototype

This is similar to function constructor but it uses prototype for their properties and methods.

function myObj(){};
myObj.prototype.name = "hello";
var k = new myObj();
Enter fullscreen mode Exit fullscreen mode

ES6 class syntax

class myObject  {
  constructor(name) {
    this.name = name;
  }
}
var e = new myObject("hello");
Enter fullscreen mode Exit fullscreen mode

Singleton pattern

A Singleton is an object which can only be instantiated one time. Repeated 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 = "Anand";
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)