January 2020
Intermediate to advanced
548 pages
13h 36m
English
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 ...Read now
Unlock full access