Applying Multiple Decorators
You'll learn how stacking multiple decorators on a single target works and in what order they execute.
Core Idea
When you apply multiple decorators to the same class member, they form a composition chain. Think of decorators like layers of wrapping paper around a gift—the innermost wrapper goes on first, then the next, and so on. In JavaScript, decorators are applied bottom-to-top (closest to the target first), but they execute top-to-bottom when called.
How Composition Works
When you stack decorators:
class Example {
@first
@second
@third
method() {}
}
The decorator closest to the method (@third) receives the original method descriptor first. Its return value becomes the input for @second, whose return value then feeds into @first.
Execution order analogy: Imagine three people wrapping a gift. The person closest to the box (@third) wraps it first. Then the next person (@second) wraps that result. Finally, the outermost person (@first) wraps everything. When you unwrap (call the method), you peel off layers in reverse—first, then second, then third.
Practical Example
function log(value, context) {
console.log(`Applying log to ${context.name}`);
return value;
}
function validate(value, context) {
console.log(`Applying validate to ${context.name}`);
return value;
}
class User {
@log
@validate
save() {}
}
// Output:
// Applying validate to save
// Applying log to save
Notice how validate (closer to the method) logs first, then log.
Key Takeaway: Multiple decorators compose bottom-to-top—the decorator nearest the target processes it first, passing results up the chain, creating powerful layered transformations.