// 类装饰器工厂函数
function methodCallCounter() {
return function (target: Function) {
const methodCalls: { [key: string]: number } = {};
const originalPrototype = target.prototype;
// 遍历类的原型上的所有方法
for (const methodName in originalPrototype) {
if (typeof originalPrototype[methodName] === 'function') {
const originalMethod = originalPrototype[methodName];
// 重写方法,每次调用增加计数器
originalPrototype[methodName] = function (...args: any[]) {
if (!methodCalls[methodName]) {
methodCalls[methodName] = 1;
} else {
methodCalls[methodName]++;
}
return originalMethod.apply(this, args);
};
}
}
// 添加一个方法用于查看所有方法的调用次数
target.prototype.getMethodCallCounts = function () {
return methodCalls;
};
};
}
// 使用装饰器
@methodCallCounter()
class MyClass {
method1() {
console.log('Method 1 called');
}
method2() {
console.log('Method 2 called');
}
}
const myClassInstance = new MyClass();
myClassInstance.method1();
myClassInstance.method1();
myClassInstance.method2();
console.log(myClassInstance.getMethodCallCounts());
装饰器工作原理说明
- 定义装饰器工厂函数
methodCallCounter
:返回一个实际的装饰器函数。
- 实际装饰器函数:接收类的构造函数
target
作为参数。
- 初始化调用次数记录对象
methodCalls
:用于存储每个方法的调用次数。
- 遍历类原型上的方法:对于每个方法,重写该方法,在方法调用前增加对应方法在
methodCalls
中的计数。
- 添加
getMethodCallCounts
方法:到类的原型上,用于获取所有方法的调用次数。
- 使用装饰器:在类定义前使用
@methodCallCounter()
,这样在类定义时,装饰器函数就会对类进行处理,重写方法并添加获取调用次数的方法。在类实例化后调用方法,调用次数会被统计,通过调用 getMethodCallCounts
方法可以查看结果。