// 定义一个装饰器工厂函数,用于创建装饰器
function addAuthorMetadata(author: string) {
return function (target: Function) {
Reflect.defineMetadata('author', author, target);
};
}
// 使用装饰器为类添加元数据
@addAuthorMetadata('John')
class MyClass {
// 类的具体实现
}
// 获取类的元数据
const author = Reflect.getMetadata('author', MyClass);
console.log(author); // 输出: John
- 装饰器工厂函数
addAuthorMetadata
:
- 它接受一个
author
参数,并返回一个真正的装饰器函数。
- 这个装饰器函数使用
Reflect.defineMetadata
方法为目标类添加 author
元数据。
- 使用装饰器:
@addAuthorMetadata('John')
将 John
作为作者元数据添加到 MyClass
类上。
- 获取元数据:
- 使用
Reflect.getMetadata
方法获取 MyClass
类上的 author
元数据,并输出。