Constructor Design Pattern — JavaScript

Ambalika Saha
2 min readJun 15, 2021

--

Photo by Elena Mozhvilo on Unsplash

What is a Constructor?

In class based Object Oriented Programming, a constructor is a special method used to create an object. It can also accept arguments to set values if there are any object properties present.

Object Creation in JS

The most common ways to create Object in Javascript are as follows:

The methods listed above are helpful when we need to create one object. There can be scenarios where we need to create many similar objects, like menu items for a nav bar or multiple users. That is achieved with constructor functions and new operator.

Constructor Functions

  • Conventionally the name starts with upper-case
  • It should always be executed with new operator.
  • Usually do not have a return statement, they write the stuff to this
  • If return is called with an object, the object is returned instead of this
  • If return is called with a primitive, that is ignored

Scope-Safe Constructors

Using the new operator is essential before all constructor functions. If we accidentally forget using the new, we will be modifying the global object instead of the newly created object.

When we call the User constructor without new, we are in fact calling a normal function. The this inside the function points to Window instead of user and as a result three global variables are created in non-strict mode. In strict mode, this would throw error.

To avoid such mishaps, scope-safe constructors come to the rescue. A scope-safe constructor returns the same result irrespective of whether the constructor function was called with or without new. The built-in constructors like Array and Object are scope-safe.

Constructor test - new.target:

Inside a function we can check whether the function was called with new operator or not with a special property new.target introduced in ES6. This value is undefined for regular functions.

In JS, constructor pattern alone comes with some inherent problems. It makes inheritance difficult. Functions like getName will be redefined for each new object created using the User constructor.

The prototype object of functions come to rescue here. All properties defined in constructor’s prototype are made available to all new objects.

In Javascript, the real power of Constructor is unleashed with the Prototype.

--

--

Ambalika Saha
Ambalika Saha

No responses yet