Auto-Accessor Decorators
What you'll learn: How to use the accessor keyword with decorators to automatically generate getter/setter pairs with customizable behavior.
The Core Idea
When you declare a field with the accessor keyword, JavaScript automatically creates a private backing field and public getter/setter methods for you. This gives you the benefits of encapsulation without manually writing get and set methods. When combined with decorators, you can intercept and customize this auto-generated getter/setter pair.
Think of it like ordering a car with automatic accessories—the manufacturer installs standard features, but you can still customize them with add-ons.
How Auto-Accessors Work
The accessor keyword tells JavaScript: "Create a getter and setter for me automatically." A decorator applied to an auto-accessor receives both the generated getter and setter functions, allowing you to wrap or replace them:
function logged(value, context) {
if (context.kind === 'accessor') {
return {
get() {
console.log(`Getting ${context.name}`);
return value.get.call(this);
},
set(val) {
console.log(`Setting ${context.name} to ${val}`);
value.set.call(this, val);
}
};
}
}
class Product {
@logged
accessor price = 100;
}
const p = new Product();
p.price; // Logs: Getting price
p.price = 150; // Logs: Setting price to 150
Without accessor, you'd need to manually define a private field and explicit getter/setter methods. The accessor keyword does this boilerplate for you, and decorators let you enhance the behavior.
Key Takeaway:
Auto-accessor decorators combine the accessor keyword with decorator functions to automatically generate and customize getter/setter pairs, reducing boilerplate while maintaining full control over property access behavior.