Method Decorators
You'll learn how to wrap, modify, or observe class methods using decorators without touching the class definition itself.
What Are Method Decorators?
Method decorators are functions that enhance or modify how class methods behave. Think of them like middleware for your methods—they intercept calls, add logging, validate parameters, or change behavior entirely, all without editing the method's source code.
A method decorator receives three arguments:
target– the class prototype (for instance methods)context– metadata about the decorated method (name, kind, access helpers)- The decorator can return a replacement function or use
context.addInitializerto run setup code
How Method Decorators Work
When you apply a decorator to a method, it runs during class definition (not at runtime). The decorator can:
- Wrap the original method to add before/after logic
- Replace the method entirely
- Observe invocations for logging, metrics, or debugging
- Validate inputs before the real method executes
function log(target, context) {
const methodName = context.name;
const originalMethod = target;
return function(...args) {
console.log(`Calling ${methodName} with`, args);
const result = originalMethod.apply(this, args);
console.log(`${methodName} returned`, result);
return result;
};
}
class Calculator {
@log
add(a, b) {
return a + b;
}
}
const calc = new Calculator();
calc.add(2, 3);
// Logs: "Calling add with [2, 3]"
// Logs: "add returned 5"
The decorator wraps add() transparently—callers see no difference, but every invocation is now logged.
Key Takeaway: Method decorators let you inject cross-cutting concerns (logging, validation, caching) into methods cleanly, keeping your class methods focused on their core logic while decorators handle the "extra" behavior.