Understanding new.target in JavaScript
📌 What is new.target?
The new.target meta-property is a special feature in JavaScript that lets you detect whether a function or constructor was called using the new keyword. It's particularly useful inside constructor functions and classes to enforce instantiation rules.
Note
💡 new.target is only defined inside constructors and functions invoked with new. It’s undefined otherwise.
🛠️ Basic Usage
Let's see how new.target works in practice:
Detecting Constructor Invocation
function Example() {
if (!new.target) {
throw new Error("Must be called with new");
}
console.log("Constructor called properly");
}
new Example(); // ✅ Works fine
Example(); // ❌ Throws errorNote
⚠️ This is a common pattern to enforce that a function behaves like a constructor and must be used with new.
🏗️ Using new.target in Classes
In ES6 classes, new.target refers to the constructor that was directly invoked with new.
new.target in Class Constructors
class Base {
constructor() {
console.log(new.target.name);
}
}
class Derived extends Base {}
new Base(); // Logs: "Base"
new Derived(); // Logs: "Derived"Note
🧠 This can help implement abstract classes by preventing direct instantiation.
🚫 Prevent Instantiating Abstract Base Classes
You can simulate abstract classes using new.target by throwing an error if the base class is instantiated directly:
Enforcing Abstract Classes
class Abstract {
constructor() {
if (new.target === Abstract) {
throw new Error("Cannot instantiate Abstract directly");
}
}
}
class RealClass extends Abstract {}
new RealClass(); // ✅ Works
new Abstract(); // ❌ Error: Cannot instantiate Abstract directly✅ Summary
- new.target is a meta-property used inside functions or constructors.
- It helps detect if a function was called using new.
- In classes, new.target points to the class that was directly instantiated.
- Useful for enforcing abstract base classes or constructor usage.
📚 Additional Resources
>>“Use new.target to write safer, smarter constructor logic.” 🚀