Ways of creating an object in Javascript

Harish Boke
3 min readMay 13, 2019

--

Javascript is mainly about objects and primitives. Primitives relates Object via coercion but, Here are some explicit ways of creating objects in Javascript.

Object: literal

Object: literal

Object literal is something wrapped in the curly braces and contain key: value pairs separated by comma, As per new ES6 if key and value are same name ie. writing it only once will also work as key-pair. see the comment in below example.

Object: Function Factory

Object: Function

In above example circle and circle1 has direct association with JS Object and prototype chain and not to createCircle

In JavaScript, any function can return a new object. When it’s not a constructor function or class, it’s called a factory function.

Object: Function Constructor

Object: Function Constructor

Unlike Factory function constructor clone and refer same object and use 4 rules of ‘new’ keyword:
1. Creates a brand new empty object
2. *Link that object to another object
3. Call function with ‘this’ set to the newly created object
4.If function does not return an object assume return of ‘this’

Object: Singleton

Object: Singleton

Single pattern doesn’t not allow object to create multiple instance like constructor. It create single instance like service hence called Singleton

Object: function constructor + prototype

Object: function constructor + prototype:

instead of adding property with `this` operator, adding function to referred prototype directly solves this use case.

This directly points constructor object and this methods access through prototype

Object: Using Object.create() method

Object: Using Object.create() method:

Constructor property — It is the linkage of Created Object parent through prototype linkage. It does not mean Object has created out of resulted object.

Object: ES6 class syntax

Object: ES6 class syntax

It is same as constructor function with syntactical sugar of class.

--

--