MST

星途 面试题库

面试题:TypeScript属性装饰器基础应用

请简要说明TypeScript中属性装饰器的定义方式,并给出一个简单示例,展示如何使用属性装饰器为类的属性添加日志功能。
34.7万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

属性装饰器定义方式

在TypeScript中,属性装饰器表达式会在运行时当作函数被调用,它会被应用到类的属性声明上。属性装饰器接收两个参数:

  1. target:对于静态成员来说是类的构造函数,对于实例成员是类的原型对象。
  2. propertyKey:属性的名称。

其基本语法如下:

function propertyDecorator(target: any, propertyKey: string | symbol) {
    // 装饰器逻辑
}

示例:为类的属性添加日志功能

function logProperty(target: any, propertyKey: string | symbol) {
    let value: any;
    const getter = function () {
        console.log(`获取 ${String(propertyKey)} 的值:`, value);
        return value;
    };
    const setter = function (newValue: any) {
        console.log(`设置 ${String(propertyKey)} 的值为:`, newValue);
        value = newValue;
    };
    if (delete target[propertyKey]) {
        Object.defineProperty(target, propertyKey, {
            get: getter,
            set: setter,
            enumerable: true,
            configurable: true
        });
    }
}

class Example {
    @logProperty
    message: string;
    constructor(message: string) {
        this.message = message;
    }
}

const example = new Example('Hello, TypeScript!');
example.message; 
example.message = 'New message'; 

在上述示例中,logProperty 是一个属性装饰器,它为 Example 类的 message 属性添加了日志功能,在获取和设置属性值时都会打印日志。