Skip to content

What are the possible ways to create objects in JavaScript?

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

Advertisements

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();

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);

Object literal syntax

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 object instances.

function Employee(name){
   var object = {};
   object.name=name;
   object.salary=1000;
   return object;
}
var object = new Person("John");
Advertisements

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();

 ES6 class syntax

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

 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";
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.