面试题答案
一键面试属性装饰器定义方式
在TypeScript中,属性装饰器表达式会在运行时当作函数被调用,它会被应用到类的属性声明上。属性装饰器接收两个参数:
target
:对于静态成员来说是类的构造函数,对于实例成员是类的原型对象。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
属性添加了日志功能,在获取和设置属性值时都会打印日志。