new.target

The new.target binding will be equal to the current function being called if the function has been called via a new operator. We typically use the new operator to instantiate classes, and in this case, we will correctly expect new.target to be that class:

class Foo {
constructor() {
console.log(new.target === Foo);
}
}
new Foo(); // => Logs: true

This is useful when we may wish to carry out a certain behavior if a constructor is called directly versus when called via new. A common defensive strategy is to make your constructor behave in the same way, regardless of whether it's called with or without new. This can be achieved by checking for new.target:

function Foo() {
if (new.target !== Foo) {
return new Foo();
}
}

new Foo() instanceof Foo; // => true
Foo() instanceof Foo; // => true

Alternatively, you may wish to throw an error to check that a constructor has been invoked incorrectly:

function Foo() {
if (new.target !== Foo) {
throw new Error('Foo is a constructor: please instantiate via new Foo()');
}
}

Foo() instanceof Foo; // !! Error: Foo is a constructor: please instantiate via new Foo()

Both of these examples would be considered intuitive use cases of new.target. There is, of course, the possibility to use it to deliver entirely different functionality depending on the calling pattern, but in the interest of catering to the reasonable expectations of programmers, it's best to avoid such behavior. Remember the POLA.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset