Object Creation Patterns in JavaScript

A run through of the four patterns in JavaScript

Kunal Tandon
Developer’s Arena
3 min readAug 4, 2019

--

JavaScripts deals with objects a lot. In this article, we’ll discuss some object creation Patterns in JavaScript.

To create objects in JS, there are various patterns that can be followed.

These patterns are:

  1. Factory pattern
  2. Constructor pattern
  3. Prototype pattern
  4. Dynamic prototype pattern

Factory Pattern

With the factory pattern, we create a factory that creates specified objects and returns their reference. Every time we call the factory we get a new instance.

Consider this example, where we want to create objects for a computer that will contain their memory capacities (ram and hard disk).

To create a factory, we write this code:

Now we create an object by calling the factory, like this:

Output:

Constructor Pattern

With the constructor pattern we don’t return the instance from the function — instead, we use the new operator along with the function name.

The constructor for the last example will be created like this:

Note: we’re not returning the object from the computer constructor.

Output:

Prototype Pattern

In JavaScript, almost every object has some prototype space that contains properties related to the object.

You can read more about prototypes in the MDN Web Docs.

In a prototype pattern, we create a blank object and assign properties (and functions) to its prototype, with some default values. Then we create a blank object and assign the actual values for the properties.

This pattern can be represented like this:

Output:

Now consider if we create a new object of the computer with default values.

var computer1 = new computer(); 
//Created object with default values
console.log('ram' in computer1); //returns true
console.log(computer1.hasOwnProperty('ram')); //returns false

This is because the in operator searches for the property first in the object's root and then the search continues in the prototype of the object whereas hasOwnProperty restricts its search to the root elements of the object in which the property is being searched.

Dynamic Prototype Pattern

The dynamic prototype pattern is a hybrid of the constructor pattern and the prototype pattern.

In this pattern properties are referenced with this operator. We create the member functions in the prototype space of the object, if the member function does not exist:

Output:

--

--