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 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
- Conventionally the name starts with upper-case
- It should always be executed with
- Usually do not have a return statement, they write the stuff to
returnis called with an object, the object is returned instead of
returnis called with a primitive, that is ignored
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
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
prototype object of functions come to rescue here. All properties defined in constructor’s prototype are made available to all new objects.