Decorator Syntax Basics
You'll learn: How to use the @ symbol to apply decorators to classes and their members.
The @ Symbol Syntax
Now that you understand what decorators are and their proposal stage, let's see how to actually write them. Decorators use the @ symbol followed by the decorator name, placed directly before the thing you're decorating.
Think of the @ symbol as a "sticky note" you attach to your code. You place it right above what you want to modify, and JavaScript automatically passes that target to your decorator function.
Basic Placement Rules
For classes:
@myDecorator
class MyClass {
// ...
}
For class methods:
class MyClass {
@myDecorator
myMethod() {
// ...
}
}
For class fields:
class MyClass {
@myDecorator
myField = 42;
}
For getters/setters:
class MyClass {
@myDecorator
get value() { return this._value; }
}
Key Points
The decorator itself is just a function you've defined elsewhere. The @ syntax is syntactic sugar that tells JavaScript: "Before finalizing this class/method/field, run it through this decorator function first."
You can stack multiple decorators vertically, and they execute from bottom to top (closest to the target runs first).
The @ must be on its own line or share a line with the decorator, not mixed with the class/method declaration itself.
Key Takeaway: Decorators use @decoratorName syntax placed immediately before class declarations or class members—this automatically invokes your decorator function with the target element.