方法装饰器,用来装饰类的方法。它接收三个参数:
target: Object - 被装饰的类的对象
key:string - 方法名
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 方法打印了调用时间。
方法装饰器的使用就介绍到这里,欢迎意见交流。
本文详细介绍了如何使用不带参数和带参数的方法装饰器,为类的方法添加日志功能,并能根据传参控制打印细节。通过Grape类实例展示了装饰器的实际应用。
622

被折叠的 条评论
为什么被折叠?



