前言
关键字
reflect-metadata
参考资料
了解 reflect-metadata 库的基本使用。
使用 reflect-metadata 库,优化 3-4. 装饰器练习。
reflect-metata
- 设置元数据:
@Reflect.metadata(metadataKey, metadataValue)
- 读取元数据:
Reflect.getMetadata(metadataKey, target)
、Reflect.getMetadata(metadataKey, target, propertyKey)
- 判断元数据是否存在:
Reflect.hasMetadata(metadataKey, target)
、Reflect.hasMetadata(metadataKey, target, propertyKey)
更多 api 见:链接
codes
import "reflect-metadata";
@Reflect.metadata("inClass", "A")
class Test {
@Reflect.metadata("inMethod", "B")
public hello(): string {
return "hello world";
}
@Reflect.metadata("prop", "test...")
test: string = "123";
}
const t = new Test();
console.log(Reflect.getMetadata("inClass", Test)); // => A
console.log(Reflect.getMetadata("inMethod", t, "hello")); // => B
console.log(Reflect.getMetadata("prop", t, "test")); // => test...
**const t = new Test()**
如何通过实例 t
获取到实例的构造器 Test
?
t.__proto__.constructor === Test
Object.getPrototypeOf(t).constructor === Test
import "reflect-metadata";
const metadataKey = Symbol("description");
// 添加元数据
export function descriptor(description: string) {
return Reflect.metadata(metadataKey, description);
}
// 打印描述信息
export function printObj(obj: any) {
const cons = obj.__proto__.constructor;
// 打印类元信息
if (Reflect.hasMetadata(metadataKey, cons)) console.log(Reflect.getMetadata(metadataKey, cons));
else console.log(cons.name);
// 打印属性元信息
for (const key in obj) {
if (Reflect.hasMetadata(metadataKey, obj, key))
console.log(
`\t${Reflect.getMetadata(metadataKey, obj, key)}: ${obj[key]}`
);
else console.log(`\t${key}: ${obj[key]}`);
}
}
const metadataKey = Symbol("description")
使用符号,防止出现元数据的 key 发生冲突。
import { descriptor, printObj } from "./Descriptors";
@descriptor("文章")
class Article {
@descriptor("标题")
title: string;
@descriptor("内容")
content: string;
@descriptor("日期")
date: Date;
}
const ar = new Article();
ar.title = "abc";
ar.content = "123";
ar.date = new Date();
printObj(ar);
import { descriptor, printObj } from "./Descriptors";
@descriptor("用户")
class User {
@descriptor("账号")
loginId: string;
@descriptor("密码")
loginPwd: string;
@descriptor("用户名")
name: string = "dahuyou";
gender: "男" | "女" = "男";
}
const u = new User();
u.loginId = "abc";
u.loginPwd = "123";
printObj(u);