New operator in javascript and 5 ways to initiate an object

New operator in javascript and 5 ways to initiate an object

How does the new operator work in Javascript, when for example, calling new MyClass(...params)?

  • Step 1: create a new object by Object.create(MyClass.prototype).
  • Step 2: call MyClass's constructor function (the MyClass itself if and only if (iff) it is a function) with this set as the object created in step 1.
  • Step 3: if the constructor returns an object, used this object as the returned value for the new operator. Otherwise, the object created in step 1 is returned.

Quirk 1:

All these expressions are equivalent:

  • {}.
  • new Object()
  • new Object // not recommended as it would produce an unintended result such as with something like new Date.getTime()
  • Object.create(Object.prototype)
  • Object.fromEntries([])
  • Reflect.construct(Object, [])

new.target operator

new.target expression is available in a constructor function's body (class's constructor or the function).

Its value is evaluated as the operand class/function of the new operator which initiates the constructor, or undefined if the function is invoked as a normal function call (i.e., without the new operator).

This is useful when you want to identify the descendant class from the ancestor's constructor, or when you want to specify whether the function is invoked with/without the new keyword.

Buy Me A Coffee