前言

使用装饰器添加描述信息。
封装输出函数,打印描述信息,更直观地查看实例身上的相关内容。

codes

  1. // 将类的描述信息保存到原型中
  2. export function classDescriptor(description: string) {
  3. return function (target: new () => object) {
  4. target.prototype.$classDescription = description;
  5. };
  6. }
  7. // 将实例属性描述信息保存到实例中
  8. export function propDescriptor(description: string) {
  9. return function (target: any, propName: string) {
  10. if (!target.$propDescriptions) target.$propDescriptions = [];
  11. target.$propDescriptions.push({
  12. propName,
  13. description,
  14. });
  15. };
  16. }
  17. // 打印描述信息
  18. export function printObj(obj: any) {
  19. // 打印类描述信息
  20. if (obj.$classDescription) console.log(obj.$classDescription);
  21. else console.log(Object.getPrototypeOf(obj).constructor.name);
  22. // 打印属性描述信息
  23. if (!obj.$propDescriptions) obj.$propDescriptions = [];
  24. for (const key in obj) {
  25. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  26. const prop = obj.$propDescriptions.find((p: any) => p.propName === key);
  27. if (prop) console.log(`\t${prop.description}: ${obj[key]}`);
  28. else console.log(`\t${key}: ${obj[key]}`);
  29. }
  30. }
  31. }
  1. import { classDescriptor, printObj, propDescriptor } from "./Descriptors";
  2. @classDescriptor("用户")
  3. class User {
  4. @propDescriptor("账号")
  5. loginId: string;
  6. @propDescriptor("密码")
  7. loginPwd: string;
  8. @propDescriptor("用户名")
  9. name: string = "dahuyou";
  10. gender: "男" | "女" = "男";
  11. }
  12. const u = new User();
  13. u.loginId = "abc";
  14. u.loginPwd = "123";
  15. printObj(u);

image.png

如果没有 @classDescriptor("用户") 类装饰器,直接打印 原型.constructor.name

image.png

原型

  • Object.getPrototypeOf(obj)
  • obj.__proto__

在原型对象身上,有一个 constructor 属性,表示构造器,通过 原型.constructor.name 可以获取到构造器的名称。

@propDescriptor()printObj
装饰器工厂 propDescriptor,仅对实例成员做了处理,并没有考虑静态成员的情况。

  1. import { classDescriptor, printObj, propDescriptor } from "./Descriptors";
  2. @classDescriptor("文章")
  3. class Article {
  4. @propDescriptor("标题")
  5. title: string;
  6. @propDescriptor("内容")
  7. content: string;
  8. @propDescriptor("日期")
  9. date: Date;
  10. }
  11. const ar = new Article();
  12. ar.title = "abc";
  13. ar.content = "123";
  14. ar.date = new Date();
  15. printObj(ar);

image.png