Декоратор метода, используемый для оформления метода класса. Он получает три параметра:
target: Object - декорируемый объект класса
ключ: строка - имя метода
descriptor: TypePropertyDescript — дескриптор свойства
1. Декоратор метода без параметров
В следующем примере показано добавление печати журнала в метод:
function log(target: any, key: string, descriptor: any) {
let method = descriptor.value;
descriptor.value = function (...args: any[]) {
var result: any = method.apply(this, args);
console.log(`method:${key}, args:${JSON.stringify(args)}, return:${result}`);
return result;
}
}
export class Grape {
price: number = 6;
constructor(price: number) {
this.price = price;
}
@log
buy(count: number): number {
return this.price * count;
}
@log
changePrice(price: number) {
this.price = price;
}
@log
sell(count: number): number {
return (this.price + 2) * count;
}
}
//组件中调用代码
let grape = new Grape(4);
grape.buy(10);
grape.changePrice(8);
grape.sell(10);
Запущенные отпечатки:
2. Декоратор методов с параметрами
Точно так же декораторы методов также позволяют передавать параметры.В следующем примере показано, следует ли печатать время вызова метода путем передачи параметров:
function log(needTime: boolean = false) {
return function (target: any, key: string, descriptor: any) {
let method = descriptor.value;
descriptor.value = function (...args: any[]) {
var result: any = method.apply(this, args);
console.log(`${needTime ? new Date().toISOString() + ", " : ""}method:${key}, args:${JSON.stringify(args)}, return:${result}`);
return result;
}
}
}
export class Grape {
price: number = 6;
constructor(price: number) {
this.price = price;
}
@log()
buy(count: number): number {
return this.price * count;
}
@log(true)
changePrice(price: number) {
this.price = price;
}
@log()
sell(count: number): number {
return (this.price + 2) * count;
}
}
//组件中调用代码
let grape = new Grape(4);
grape.buy(10);
grape.changePrice(8);
grape.sell(10);
Запущенные отпечатки:
В приведенном выше примере только параметр, переданный, когда метод changePrice добавляет декоратор, имеет значение true , поэтому только метод changePrice печатает время вызова при печати .
Здесь представлено использование декораторов методов, добро пожаловать на обмен мнениями.