MST

星途 面试题库

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

请用TypeScript编写一个属性装饰器,用于在类的属性被访问时打印一条日志,说明属性被访问了。并给出使用该装饰器的类示例。
48.4万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
function logAccess(target: any, propertyKey: string) {
    let value: any;
    const getter = function () {
        console.log(`${propertyKey} 被访问了`);
        return value;
    };
    const setter = function (newValue: any) {
        value = newValue;
    };
    if (delete target[propertyKey]) {
        Object.defineProperty(target, propertyKey, {
            get: getter,
            set: setter,
            enumerable: true,
            configurable: true
        });
    }
}

class ExampleClass {
    @logAccess
    public message: string = 'Hello, World!';
}

const example = new ExampleClass();
console.log(example.message);