How to create objects in JavaScript?

Spread the love

 

In this article, we are going to learn multiple ways to create objects in Javascript.

Multiple Ways To Create Objects in Javascript

1. Object Constructor

This is the simple way to create an object in Javascript.

var object = new Object();

However, this approach is not recommended these days as we can an object with the new keyword.

var object = Object();

2. Create() Method of Object

This can be used to create a new object by passing the prototype object and properties as arguments. This pattern is helpful if we want to create a new object based on the existing object. The second argument is optional and it is used to create properties on newly created objects.

var object = Object.create(null);

3. Object Literal Syntax

This way, we simply add key-value pairs separated by commas inside curly braces.

var object = {
     name: "John",
     age: 28
};

These values can be of any data type including array, function and nested object.

4. Function constructor

In this method, we will create a function and apply the new operator to object to that function

function Person(name) {
  this.name = name;
  this.age = 23;
}
var object = new Person("John");

5. ES6 Class Syntax

In ES6 we have newly introduced class feature to create objects.

class Person {
  constructor(name) {
    this.name = name;
  }
}

var object = new Person("Tony");

6. Singleton Pattern

A singleton is a class that holds only one instance. So, we can create an object using a singleton, and even if we have repeated calls to its constructor, it will return the same instance.

var object = new (function () {
  this.name = "Sudheer";
})();

 

Leave a Comment