JS: new.target
new.target
(new in ECMAScript 2015)
xtodonew.target is a special meta-property in JavaScript that tells you whether a function (or class constructor) was invoked using the new keyword.
Simple Explanation
- When you call a function with
new:new.targetrefers to the constructor/function that was called. - When you call it normally (without
new):new.targetisundefined.
This is very useful for:
- Enforcing that a constructor is always used with
new - Handling inheritance in classes (it returns the actual subclass when inherited)
Basic Examples
1. In a regular function:
function User(name) { console.log(new.target); // ← this is the key if (!new.target) { return new User(name); // auto-fix: call with new } this.name = name; } // Usage User("Alice"); // new.target === undefined → auto creates with new new User("Bob"); // new.target === User function
2. In a class:
class Animal { constructor() { console.log(new.target); // Shows which constructor was actually used } } class Dog extends Animal { constructor() { super(); } } new Animal(); // → Animal new Dog(); // → Dog (this is the powerful part for inheritance)
Common Use Cases
-
Prevent accidental calls without
new(make functions non-constructible):function mustBeCalledWithNew() { if (!new.target) { throw new Error("Must be called with new"); } } -
Auto-correct missing
new(as in the first example). -
Factory pattern or flexible constructors that behave differently based on how they're called.
Key Points
new.targetonly works inside functions or class constructors. Using it outside throws a syntax error.- It was introduced in ES2015 (ES6) and is supported in all modern browsers.
- In arrow functions,
new.targetis not available (they inherit it from the enclosing scope).
This meta-property solves a long-standing issue in JavaScript where it was hard to reliably know if new was used.