When do decorators get executed?
class Person {
@SomeDecorator
age
}
What about static properties?
A Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter. Decorators use the form @expression , where expression must evaluate to a function that will be called at runtime with information about the decorated declaration.
A Decorator is a special kind of declaration that can be applied to classes, methods, accessor, property, or parameter.
Decorators are the way of wrapping one piece of code with another or apply a wrapper around a function in JavaScript. Decorators are the design pattern that allows behavior to be added to an individual object, either statically or dynamically without affecting the behavior of other objects from the same class.
There are five ways to use decorators and we will look at examples of each one.
A property decorator executes early - when the class is defined. You don't need to construct an instance, or access the property.
Example: this logs age
without the Person
class even being constructed. The same applies if the property is static.
function SomeDecorator(a, b) {
console.log(b);
}
class Person {
@SomeDecorator
public age: number;
}
If you are after hooking into the get and set actions on the property - that is possible too. Here is an example from a listing in Pro TypeScript (Second Edition). It works by wrapping the getter and setter.
function log(target: any, key: string) {
let value = target[key];
// Replacement getter
const getter = function () {
console.log(`Getter for ${key} returned ${value}`);
return value;
};
// Replacement setter
const setter = function (newVal) {
console.log(`Set ${key} to ${newVal}`);
value = newVal;
};
// Replace the property
if (delete this[key]) {
Object.defineProperty(target, key, {
get: getter,
set: setter,
enumerable: true,
configurable: true
});
}
}
class Calculator {
@log
public num: number;
square() {
return this.num * this.num;
}
}
console.log('Construct');
const calc = new Calculator();
console.log('Set');
// Set num to 4
calc.num = 4;
console.log('Get');
// Getter for num returned 4
// Getter for num returned 4
calc.square();
The output of this listing is:
Construct (manual log)
Set (manual log)
-> Set num to 4
Get (manual log)
-> Getter for num returned 4
-> Getter for num returned 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With