Field Decorators and Initialization
You'll learn how field decorators can intercept and control the initialization of class fields, enabling dependency injection, reactivity, and validation.
What Field Decorators Control
Field decorators run when the class is defined, but they influence what happens when each instance is created. Unlike method decorators (which wrap existing functions), field decorators let you replace or enhance the initialization logic for a field. Think of them as gatekeepers that can intercept the moment a field gets its value.
The Initialization Hook
When you decorate a field, your decorator receives the context object with an addInitializer method. This lets you register code that runs during instance construction, after the field has been assigned but before the constructor body executes:
function reactive(value, context) {
context.addInitializer(function() {
console.log(`Initializing ${context.name} with:`, this[context.name]);
});
}
class Store {
@reactive
count = 0;
constructor() {
console.log('Constructor running');
}
}
const store = new Store();
// Logs: "Initializing count with: 0"
// Then: "Constructor running"
Controlling the Value
Your decorator can also return a new initializer function that replaces the original assignment:
function doubled(value, context) {
return function(initialValue) {
return initialValue * 2;
};
}
class Math {
@doubled
score = 5;
}
const m = new Math();
console.log(m.score); // 10 (doubled from 5)
This enables dependency injection (return an injected service), validation (throw if invalid), or reactivity systems (wrap values in observable proxies).
Key Takeaway: Field decorators intercept initialization, letting you inject logic, transform values, or add side effects at the moment each instance's field is set—perfect for frameworks that need control over class property creation.