function accessCounter(target: any, propertyKey: string) {
let count = 0;
const originalGetter = Object.getOwnPropertyDescriptor(target, propertyKey)?.get;
if (originalGetter) {
Object.defineProperty(target, propertyKey, {
get() {
count++;
console.log(`${propertyKey} 被访问了 ${count} 次`);
return originalGetter.call(this);
}
});
}
}
class ExampleClass {
@accessCounter
public myProperty: string = 'Hello, World!';
}
const example = new ExampleClass();
console.log(example.myProperty);
console.log(example.myProperty);