new Keyword

Description

When a function is called with the new keyword, the function will be used as a constructor. new will do the following things:

  1. Creates a blank, plain JavaScript object. For convenience, let's call it newInstance.
  2. Points newInstance's [[Prototype]] to the constructor function's prototype property.

    Note: Properties/objects added to the constructor function's prototype property are therefore accessible to all instances created from the constructor function.

  3. Executes the constructor function with the given arguments, binding newInstance as the this context (i.e. all references to this in the constructor function now refer to newInstance).
  4. If the constructor function returns a non-primitive, this return value becomes the result of the whole new expression. Otherwise, if the constructor function doesn't return anything or returns a primitive, newInstance is returned instead. (Normally constructors don't return a value, but they can choose to do so to override the normal object creation process.)

Classes can only be instantiated with the new operator — attempting to call a class without new will throw a TypeError.

Creating an object with a user-defined constructor function requires two steps:

  1. Define the object type by writing a function that specifies its name and properties. For example, a constructor function to create an object Foo might look like this:
    function Foo(bar1, bar2) {
      this.bar1 = bar1;
      this.bar2 = bar2;
    }
    
  • Create an instance of the object with new.
    const myFoo = new Foo('Bar 1', 2021);
    

Note: An object can have a property that is itself another object. See the examples below.

You can always add a property to a previously defined object instance. For example, the statement car1.color = "black" adds a property color to car1, and assigns it a value of "black".

However, this does not affect any other objects. To add the new property to all objects of the same type, you must add the property to the constructor's prototype property. This defines a property that is shared by all objects created with that function, rather than by just one instance of the object type. The following code adds a color property with value "original color" to all objects of type Car, and then overwrites that value with the string "black" only in the instance object car1. For more information, see prototype.

function Car() {}
const car1 = new Car();
const car2 = new Car();

console.log(car1.color);    // undefined

Car.prototype.color = 'original color';
console.log(car1.color);    // 'original color'

car1.color = 'black';
console.log(car1.color);    // 'black'

console.log(Object.getPrototypeOf(car1).color); // 'original color'
console.log(Object.getPrototypeOf(car2).color); // 'original color'
console.log(car1.color);   // 'black'
console.log(car2.color);   // 'original color'

Note: While the constructor function can be invoked like any regular function (i.e. without the new operator), in this case a new object is not created and the value of this is also different.

A function can know whether it is invoked with new by checking new.target. new.target is only undefined when the function is invoked without new. For example, you can have a function that behaves differently when it's called versus when it's constructed:

function Car(color) {
  if (!new.target) {
    // Called as function.
    return `${color} car`;
  }
  // Called with new.
  this.color = color;
}

const a = Car("red"); // a is "red car"
const b = new Car("red"); // b is `Car { color: "red" }`

Prior to ES6, which introduced classes, most JavaScript built-ins are both callable and constructible, although many of them exhibit different behaviors. To name a few:

  • Array(), Error(), and Function() behave the same when called as a function or a constructor.
  • Boolean(), Number(), and String() coerce their argument to the respective primitive type when called, and return wrapper objects when constructed.
  • Date() returns a string representing the current date when called, equivalent to new Date().toString().

After ES6, the language is stricter about which are constructors and which are functions. For example:

  • Symbol() and BigInt() can only be called without new. Attempting to construct them will throw a TypeError.
  • Proxy and Map can only be constructed with new. Attempting to call them will throw a TypeError.