Method decorator, used to decorate the method of the class. It receives three parameters:
target: Object - the object of the class being decorated
key: string - method name
descriptor: TypePropertyDescript - the property descriptor
1. Method decorator without parameters
The following example demonstrates adding log printing to a method:
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);
Running prints:
2. Method decorator with parameters
Similarly, method decorators also allow parameters to be passed. The following example demonstrates whether to print method call time by passing parameters:
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);
Running prints:
In the above example, only the parameter passed when the changePrice method adds a decorator is true , so only the changePrice method prints the calling time when printing .
The use of method decorators is introduced here, welcome to exchange opinions.