Jeśli dekoratory to dla Ciebie obcy temat to zapraszam do wprowdzenia.
Kiedy uruchamiane są dekoratory?
Dekoratory (a w gruncie rzeczy to funkcje je obsługujące) są odpalane w tym samym momencie gdy ładowana jest przez interpreter definicja klasy. Stąd dekoratory są odpalane tylko raz dla każdego wystąpienia (jeśli dekorator jest użyty w wielu miejscach to zostanie uruchomiony dla każdego wystąpienia).
Kolejność
Dekoratory wykonują się od dołu do góry. Jedynie stworzenie dekoratorów przyjmujących argumenty (decorator factory) odbywa się zgodnie z kolejnością linijek w kodzie:
function ClassDecorator(constructorFunction: Function){
console.log(`I'm a decorator 1`);
};
function ClassDecorator2(constructorFunction: Function){
console.log(`I'm a decorator 2`);
};
function ArgumentsInDecorator(times: number){
console.log('ArgumentsInDecorator1');
return function(constructorFunction: Function){
for (let i = 0; i < times; i++) {
console.log(`I'm a decorator 1 with arguments 1`);
}
}
};
function ArgumentsInDecorator2(times: number){
console.log('ArgumentsInDecorator2');
return function(constructorFunction: Function){
for (let i = 0; i < times; i++) {
console.log(`I'm a decorator 2 with arguments`);
}
}
};
@ArgumentsInDecorator(1)
@ArgumentsInDecorator2(1)
@ClassDecorator
@ClassDecorator2
class Car {
name: string;
manufacturer: string;
productionYear: number;
constructor(name: string){
this.name = name;
}
}Powyższy kod zwraca w konsoli:
ArgumentsInDecorator1
ArgumentsInDecorator2
I'm a decorator 2
I'm a decorator 1
I'm a decorator 2 with arguments
I'm a decorator 1 with argumentsWarto zajrzeć
1. https://www.typescriptlang.org/docs/handbook/decorators.html
2. Nadpisywanie za pomocą dekoratorów
