The new.target
syntax is available in all functions. In constructors, new.target
refers to the constructor that was invoked by new
. In normal function calls, new.target
is {{jsxref("undefined")}}.
Syntax
new.target
Description
The new.target syntax consists of the keyword "new
", a dot, and a property name "target"
. Normally "new."
serves as the context for a property access, but here "new."
is not really an object. In a constructor calls, however, new.target
refers the constructor invoked by new
and so "new.
" becomes a virtual context here.
new.target
is a meta property that is available to all functions. In arrow functions, new.target
refers to the new.target
of the surrounding function.
Examples
new.target
in function calls
In normal function calls (as opposed to constructor function calls), new.target
is {{jsxref("undefined")}}. This lets you detect if a function was called with new as a constructor or not:
function Foo() { if (!new.target) throw "Foo() must be called with new"; console.log("Foo instantiated with new"); } Foo(); // throws "Foo() must be called with new" new Foo(); // logs "Foo instantiated with new"
new.target
in constructors
In class constructors, new.target
refers to the constructor that was directly invoked by new
. This is also the case if the constructor is in a parent class and was delegated from a child constructor.
class A { constructor() { console.log(new.target.name); } } class B extends A { constructor() { super(); } } var a = new A(); // logs "A" var b = new B(); // logs "B"
Specifications
Specification | Status | Comment |
---|---|---|
{{SpecName('ES6', '#sec-built-in-function-objects', 'Built-in Function Objects')}} | {{Spec2('ES6')}} | Initial definition. |
Browser compatibility
{{CompatibilityTable}}
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | {{CompatNo}} | {{CompatGeckoDesktop(41)}} | {{CompatNo}} | {{CompatNo}} | {{CompatNo}} |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | {{CompatNo}} | {{CompatNo}} | {{CompatGeckoMobile(41)}} | {{CompatNo}} | {{CompatNo}} | {{CompatNo}} |