Class Decorators and Constructor Replacement
What you'll learn: How class decorators can wrap or completely replace a class's constructor to control instantiation behavior and inject metadata.
The Power to Replace a Constructor
While earlier lessons showed how class decorators can add metadata or wrap methods, one of their most powerful capabilities is constructor replacement. A class decorator can return a completely new constructor function that replaces the original class. This new constructor can call the original, modify its behavior, or even create instances of an entirely different class.
Think of it like a vending machine that dispenses surprise upgrades: you press the button for a regular soda, but the machine wraps it in a insulated sleeve and adds a straw before handing it to you. The decorator intercepts instantiation and enhances what comes out.
How Constructor Replacement Works
When a class decorator returns a new class or constructor function, that replacement becomes what users actually instantiate. The original class is provided as the first argument to the decorator, and you can reference it inside your replacement:
function addTimestamp(OriginalClass, context) {
// Return a replacement class that extends the original
return class extends OriginalClass {
constructor(...args) {
super(...args); // Call original constructor
this.createdAt = new Date();
}
};
}
@addTimestamp
class User {
constructor(name) {
this.name = name;
}
}
const user = new User("Alice");
console.log(user.createdAt); // Current timestamp
The decorator wraps the original constructor, calls it via super(), then adds the createdAt field automatically.
When to Use This Pattern
Constructor replacement shines when you need to:
- Add properties to every instance automatically
- Log or track instantiation
- Implement singleton patterns
- Add validation before construction
- Inject dependencies
Key Takeaway: Class decorators can return replacement constructors that wrap or completely override the original class, giving you full control over instantiation behavior while preserving the class's identity.