MST
星途 面试题库

面试题:TypeScript属性装饰器的基本用法

请用TypeScript编写一个简单的属性装饰器,用于记录属性被访问的次数,并在控制台打印出来。要求给出完整的类和装饰器代码示例。
40.8万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
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);