Composing Multiple Decorators
You'll learn how multiple decorators applied to the same method execute in a specific order and how they interact with each other.
How Decorator Stacking Works
When you apply multiple decorators to a single method, they execute in reverse order — from bottom to top. The decorator closest to the method definition wraps the method first, then the next decorator wraps that result, and so on. Think of it like wrapping a gift in multiple layers: the innermost wrapping goes on first, then each outer layer wraps what's already there.
Execution Order
function first(method, context) {
console.log("First decorator applied");
return function(...args) {
console.log("First: before");
const result = method.apply(this, args);
console.log("First: after");
return result;
};
}
function second(method, context) {
console.log("Second decorator applied");
return function(...args) {
console.log("Second: before");
const result = method.apply(this, args);
console.log("Second: after");
return result;
};
}
class Example {
@second
@first
greet() {
console.log("Hello!");
}
}
// Logs during class definition:
// "First decorator applied"
// "Second decorator applied"
new Example().greet();
// "Second: before"
// "First: before"
// "Hello!"
// "First: after"
// "Second: after"
The decorators are applied bottom-to-top (@first then @second), but execute top-to-bottom (@second wraps the result of @first).
Practical Composition
You can combine timing, logging, and validation decorators seamlessly. Each decorator enhances the method independently, and their combined effect creates powerful behavior.
Key Takeaway: Multiple decorators stack bottom-to-top during application but execute in reverse order at runtime, allowing you to compose reusable method enhancements like layers of behavior.