前言
使用装饰器添加描述信息。
封装输出函数,打印描述信息,更直观地查看实例身上的相关内容。
codes
// 将类的描述信息保存到原型中
export function classDescriptor(description: string) {
return function (target: new () => object) {
target.prototype.$classDescription = description;
};
}
// 将实例属性描述信息保存到实例中
export function propDescriptor(description: string) {
return function (target: any, propName: string) {
if (!target.$propDescriptions) target.$propDescriptions = [];
target.$propDescriptions.push({
propName,
description,
});
};
}
// 打印描述信息
export function printObj(obj: any) {
// 打印类描述信息
if (obj.$classDescription) console.log(obj.$classDescription);
else console.log(Object.getPrototypeOf(obj).constructor.name);
// 打印属性描述信息
if (!obj.$propDescriptions) obj.$propDescriptions = [];
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
const prop = obj.$propDescriptions.find((p: any) => p.propName === key);
if (prop) console.log(`\t${prop.description}: ${obj[key]}`);
else console.log(`\t${key}: ${obj[key]}`);
}
}
}
import { classDescriptor, printObj, propDescriptor } from "./Descriptors";
@classDescriptor("用户")
class User {
@propDescriptor("账号")
loginId: string;
@propDescriptor("密码")
loginPwd: string;
@propDescriptor("用户名")
name: string = "dahuyou";
gender: "男" | "女" = "男";
}
const u = new User();
u.loginId = "abc";
u.loginPwd = "123";
printObj(u);
如果没有 @classDescriptor("用户")
类装饰器,直接打印 原型.constructor.name
原型
Object.getPrototypeOf(obj)
obj.__proto__
在原型对象身上,有一个 constructor 属性,表示构造器,通过 原型.constructor.name
可以获取到构造器的名称。
@propDescriptor()
、printObj
装饰器工厂 propDescriptor,仅对实例成员做了处理,并没有考虑静态成员的情况。
import { classDescriptor, printObj, propDescriptor } from "./Descriptors";
@classDescriptor("文章")
class Article {
@propDescriptor("标题")
title: string;
@propDescriptor("内容")
content: string;
@propDescriptor("日期")
date: Date;
}
const ar = new Article();
ar.title = "abc";
ar.content = "123";
ar.date = new Date();
printObj(ar);