The Magic of Annotations
Decorators are a special @ syntax that let you " wrap " classes and their methods to add new behavior without modifying the original code. Think of them as reusable modifiers.
Warning
Decorators are in the process of being finalized in the JavaScript standard. For current use in projects, you typically need TypeScript or Babel configured with the decorators plugin.
// Example of what decorators look like in practice:
@singleton // Only one instance of this class can exist
@logged // Log all method calls automatically
class UserService {
@readonly // This property cannot be changed after creation
id = generateId();
@memoize // Cache the result of this method
fetchUserData(userId) {
return fetch('/api/users/' + userId);
}
}
How Decorators Work
A decorator is simply a function that receives a class or method as its argument and returns a modified version:
function readonly(target, key, descriptor) {
descriptor.writable = false;
return descriptor;
}
Tip
You can already encounter decorators in popular frameworks like Angular (@Component, @Injectable) and state management libraries like MobX (@observable, @action). They are one of the most powerful metaprogramming tools available.