Constructor Design Pattern — JavaScript

Photo by Elena Mozhvilo on Unsplash

What is a Constructor?

Object Creation in JS

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

  • 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

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:

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.

--

--

Javascript Enthusiast

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store