1. 装饰器

1. 装饰器的意义

装饰器是前端了不起的技术革命,弥补了只有后端语言才有 AOP(类似装饰器)的短板,学习装饰器好处有:

  1. 较大提升前端架构思维和前端架构能力,装饰器底层蕴含的拦截器思想在Java Spring, Nest.js框架,python各种后端语言中都有广泛的应用,而拦截器展示的就是一种架构思维,通过学习装饰器能扩大技术视野,是作为一名前端架构师以及更高职位必会技能。
  2. Nestjs 等相对新型的 Nodejs 框架大量运用了 TS 装饰器,例如: @Controller @Service @Get @Post
  3. 在面试中,如果告诉面试官,你精通装饰器,这也能成为你的大加分项,因为公司更需架构思维能力强的前端工程师,因为具有架构思维的前端开发人员在大中项目中一定能写出扩展性更好的代码。

    2. 装饰器的定义和分类

    :::info 【定义】装饰器就是一个方法,可以注入到类、方法、属性、参数和对象上,拓展其功能。 ::: :::success 装饰器要解决的问题
    装饰器就是解决在不修改原来类、方法、属性和参数的时候,为其添加额外的功能。比如:

  4. 为整个项目的所有业务类的所有方法都增加日志信息,如果一个个增加,那就要修增加大量的语句。假如日后日志文件格式发生了变化,也还需要修改300次。如果有了装饰器,只需要修改一次即可。

  5. 在Nest.js中装饰器可以解决依赖注入的问题,而依赖注入是Java等后端语言拥有的非常优秀的编程思想;有了依赖注入,可以大大降低项目的耦合度,大大提升项目的可拓展性。 ::: 装饰器的分类
    常见的装饰器:类装饰器、属性装饰器、方法装饰器、参数装饰器、元数据装饰器。

    2. 类装饰器

    1. 类装饰器的实现

    :::info 装饰器可分为:带参数的装饰器和不带参数的装饰器 ::: ```typescript // 不带参数的装饰器 function FirstClassDecorator(targetClass: any) { let targetClassObj = new targetClass(); targetClassObj.buy(); console.log(“targetClass.name: “, targetClass.name); }

// 带参数类装饰器案例 function FirstClassDecoratorParam(classinfo: string) { return function (targetClass: any) { console.log(targetClass.prototype.constructor.name + “ “ + classinfo); Object.keys(targetClass.prototype).forEach((methodname) => { console.log(“方法”, methodname); let dataprop = Object.getOwnPropertyDescriptor( targetClass.prototype, methodname ); console.log(“方法数据属性:”, dataprop); }); }; }

@FirstClassDecoratorParam(“param”) class CustomerService { name: string = “下单”; constructor() {} buy() { console.log(this.name + “购买”); } placeOrder() { console.log(this.name + “下单购买”); } }

  1. <a name="u5oy3"></a>
  2. ## 2. 类装饰器的JS源码
  3. ```typescript
  4. "use strict";
  5. // 1. 底层JS 组合装饰器和目标类 __decorate函数
  6. var __decorate =
  7. (this && this.__decorate) ||
  8. function (decorators, target, key, desc) {
  9. // argsnum 参数个数
  10. var argsnum = arguments.length;
  11. // targetinfo 被装饰器修饰的目标(本案例为类)
  12. // argsnum=2 装饰器修饰的是类或者构造器参数,targetinfo=target[类名]
  13. // argsnum=4 装饰器修饰的是方法(第四个参数desc等于null),
  14. // targetinfo=该方法的数据属性
  15. // desc = Object.getOwnPropertyDescriptor(target, key)
  16. // argsnum=3 装饰器修饰的是方法参数或者属性,targetinfo=undefined
  17. var targetinfo =
  18. argsnum < 3
  19. ? target
  20. : desc === null
  21. ? (desc = Object.getOwnPropertyDescriptor(target, key))
  22. : desc; //S100
  23. // decorator保存装饰器数组元素
  24. var decorator;
  25. // 元数据信息,支持reflect-metadata元数据
  26. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
  27. targetinfo = Reflect.decorate(decorators, target, key, desc);
  28. }
  29. // 装饰器循环,倒着循环,说明同一个目标上有多个装饰器,执行顺序是倒着执行
  30. else
  31. for (var i = decorators.length - 1; i >= 0; i--) {
  32. if ((decorator = decorators[i])) {
  33. // 如果参数小于3【decorator为类装饰器或者构造器参数装饰器】
  34. // 执行decorator(targetinfo)直接执行decorator装饰器,并传递目标targetinfo,这里是类
  35. // 如果参数大于3【decorator为方法装饰器】 直接执行 decorator(target, key, targetinfo)
  36. // 如果参数等于3 【decorator为方法参数装饰器或者属性装饰器】 直接执行decorator(target, key)
  37. // targetinfo最终为各个装饰器执行后的返回值,但如果没有返回值,直接返回第S100行的targetinfo
  38. targetinfo =
  39. (argsnum < 3
  40. ? decorator(targetinfo)
  41. : argsnum > 3
  42. ? decorator(target, key, targetinfo)
  43. : decorator(target, key)) || targetinfo;
  44. console.log("targetinforesult:", targetinfo);
  45. }
  46. }
  47. return (
  48. argsnum > 3 &&
  49. targetinfo &&
  50. Object.defineProperty(target, key, targetinfo),
  51. targetinfo
  52. );
  53. };
  54. // 底层JS 组合装饰器和目标类 __decorate函数结束
  55. // 不带参数的装饰器
  56. function FirstClassDecorator(targetClass) {
  57. var targetClassObj = new targetClass();
  58. targetClassObj.buy();
  59. console.log("targetClass.name:", targetClass.name);
  60. }
  61. var CustomerService = /** @class */ (function () {
  62. function CustomerService() {
  63. this.name = "下单";
  64. }
  65. CustomerService.prototype.buy = function () {
  66. console.log(this.name + "购买");
  67. };
  68. CustomerService.prototype.placeOrder = function () {
  69. console.log(this.name + "下单购买");
  70. };
  71. CustomerService = __decorate([FirstClassDecorator], CustomerService);
  72. return CustomerService;
  73. })();
  74. // 带参数类装饰器案例
  75. function FirstClassDecoratorParam(classinfo) {
  76. return function (targetClass) {
  77. console.log(targetClass.prototype.constructor.name + " " + classinfo);
  78. Object.keys(targetClass.prototype).forEach((methodname) => {
  79. console.log("方法", methodname);
  80. let dataprop = Object.getOwnPropertyDescriptor(
  81. targetClass.prototype,
  82. methodname
  83. );
  84. console.log("方法数据属性:", dataprop);
  85. });
  86. };
  87. }
  88. let CustomerService = class CustomerService {
  89. constructor() {
  90. this.name = "下单";
  91. }
  92. buy() {
  93. console.log(this.name + "购买");
  94. }
  95. placeOrder() {
  96. console.log(this.name + "下单购买");
  97. }
  98. };
  99. CustomerService = __decorate(
  100. [FirstClassDecoratorParam("param"), __metadata("design:paramtypes", [])],
  101. CustomerService
  102. );

3. 泛型工厂类继承装饰器

:::info 需求:对已经开发好的项目中的任意一个类,创建实例时,打印日志信息,输出哪一个类被创建了,并输出参数 :::

  1. function LoggerInfoDecorator<T extends { new (...args: any): any }>(
  2. targetClass: T
  3. ) {
  4. class LoggerSonClass extends targetClass {
  5. constructor(...args: any) {
  6. super(...args);
  7. console.log("日志信息...", targetClass.name);
  8. }
  9. methodone() {
  10. console.log("methodone:", this.name);
  11. }
  12. }
  13. return LoggerSonClass;
  14. }
  15. @LoggerInfoDecorator
  16. class Test {
  17. name!: string;
  18. age!: number;
  19. constructor(name: string) {
  20. this.name = name;
  21. }
  22. eat() {
  23. console.log(this.name, "吃饭");
  24. }
  25. }
  26. let test = new Test("wer"); //LoggerSonClass
  27. (test as any).methodone();
  28. // type TestConstructorType = new (...args: any) => Test;
  29. //let LoggerSonClass = LoggerInfoDecorator<TestConstructorType>(Test)
  30. let LoggerSonClass = LoggerInfoDecorator<typeof Test>(Test);
  31. let LoggerSonClassInstance = new LoggerSonClass("xiaoming");
  32. LoggerSonClassInstance.methodone();
  33. export {};

TS支持匿名类,所以装饰器也可以这么写

  1. function LoggerInfoDecorator<T extends { new (...args: any): any }>(
  2. targetClass: T
  3. ) {
  4. return class extends targetClass {
  5. constructor(...args: any) {
  6. super(...args);
  7. console.log("日志信息...", targetClass.name);
  8. }
  9. methodone() {
  10. console.log("methodone:", this.name);
  11. }
  12. };
  13. }

3. 方法装饰器

1. 方法装饰器的实现

  1. /**
  2. *
  3. * @param targetClassPrototype
  4. * @param methodName
  5. * @param methodDesc 数据属性
  6. */
  7. function MyMethodDecorator(
  8. targetClassPrototype: any,
  9. methodName: string,
  10. methodDesc: PropertyDescriptor
  11. ) {
  12. console.log("targetClassPrototype: ", targetClassPrototype);
  13. console.log("methodName: ", methodName);
  14. console.log("mehodDesc: ", methodDesc);
  15. methodDesc.value();
  16. }
  17. function MyMethodDecoratorWithParam(methodPath: string) {
  18. return function (
  19. targetClassPrototype: any,
  20. methodName: string,
  21. methodDesc: PropertyDescriptor
  22. ) {
  23. console.log("methodPath: ", methodPath);
  24. console.log("targetClassPrototype: ", targetClassPrototype);
  25. console.log("methodName: ", methodName);
  26. console.log("mehodDesc: ", methodDesc);
  27. methodDesc.value(); // 可以直接执行传入的方法
  28. };
  29. }
  30. class RoleService {
  31. public roleName: string = "管理员";
  32. constructor() {}
  33. @MyMethodDecorator
  34. @MyMethodDecoratorWithParam("test")
  35. DistribRoles() {
  36. console.log("分配角色.....");
  37. }
  38. }
  39. export {};

2. 方法装饰器拦截器的意义

:::warning 在方法装饰器中拦截目标类的方法,可以壮大或者修改目标类的方法和功能。
比如:增加一个日志信息,采取该方法参数进行功能拓展处理。 ::: :::success 前置拦截:在方法执行前对方法进行处理
后置拦截:执行完方法后还有做别的事情 ::: 实现一个简单的拦截器: 去除参数中的空格

  1. // 方法装饰器
  2. class StringUtil {
  3. //工具类
  4. public static trimSpace(str: string): string {
  5. return str.replace(/\s+/g, "");
  6. }
  7. }
  8. function MethodInterceptor(methodPath: string) {
  9. return function (
  10. targetClassPrototype: any,
  11. methodName: string,
  12. methodDesc: PropertyDescriptor
  13. ) {
  14. let targetMethodSave = methodDesc.value;
  15. //实现一个拦截器
  16. methodDesc.value = function (...args: any) {
  17. args = args.map((arg: any) => {
  18. if (typeof arg === "string") {
  19. return StringUtil.trimSpace(arg);
  20. }
  21. return arg;
  22. });
  23. targetMethodSave.apply(this, args);
  24. };
  25. };
  26. }
  27. class RoleService {
  28. public roleName: string = "管理员";
  29. constructor() {}
  30. @MethodInterceptor("test")
  31. DistribRoles(userName: string) {
  32. // 分配角色
  33. console.log("分配角色: ", userName);
  34. }
  35. }
  36. let roleService = new RoleService();
  37. roleService.DistribRoles("xiao ming");
  38. export {};

3. 底层JS源码

  1. "use strict";
  2. // 1. 底层JS 组合装饰器和目标类 __decorate函数
  3. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  4. // argsnum 参数个数
  5. var argsnum = arguments.length;
  6. // targetinfo 被装饰器修饰的目标
  7. // argsnum=2 装饰器修饰的是类或者构造器参数,targetinfo=target[类名]
  8. // argsnum=4 装饰器修饰的是方法 [第四个参数desc等于null]
  9. // targetinfo=该方法的数据属性【desc = Object.getOwnPropertyDescriptor(target, key) 】
  10. // argsnum=3 装饰器修饰的是方法参数或者属性,targetinfo=undefined
  11. var targetinfo = argsnum < 3 ? target : desc === null ?
  12. desc = Object.getOwnPropertyDescriptor(target, key) : desc;
  13. // decorator保存装饰器数组元素
  14. var decorator;
  15. // 元数据信息,支持reflect-metadata元数据
  16. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
  17. targetinfo = Reflect.decorate(decorators, target, key, desc);
  18. } else
  19. // 装饰器循环,倒着循环,说明同一个目标上有多个装饰器,执行顺序是倒着执行
  20. for (var i = decorators.length - 1; i >= 0; i--) {
  21. if (decorator = decorators[i]) {
  22. // 如果参数小于3【decorator为类装饰器或者构造器参数装饰器】
  23. // 执行decorator(targetinfo)直接执行decorator装饰器,并传递目标targetinfo
  24. // 如果参数大于3【decorator为方法装饰器】
  25. // 直接执行 decorator(target, key, targetinfo)
  26. // 如果参数等于3 【decorator为方法参数装饰器或者属性装饰器】
  27. // 直接执行decorator(target, key)
  28. // targetinfo最终为各个装饰器执行后的返回值,但如果没有返回值,直接返回targetinfo
  29. targetinfo = (argsnum < 3 ? decorator(targetinfo) : argsnum > 3 ?
  30. decorator(target, key, targetinfo) : decorator(target, key)) || targetinfo;
  31. console.log("targetinforesult:", targetinfo)
  32. }
  33. }
  34. return argsnum > 3 && targetinfo && Object.defineProperty(target, key, targetinfo), targetinfo;
  35. }
  36. Object.defineProperty(exports, "__esModule", { value: true });
  37. // 底层JS 组合装饰器和目标类 __decorate函数结束
  38. // 2. 工具类
  39. var StringUtil = /** @class */ (function () {
  40. function StringUtil () {
  41. }
  42. StringUtil.trimSpace = function (str) {
  43. return str.replace(/\s+/g, "");
  44. };
  45. return StringUtil;
  46. }());
  47. // 目标类
  48. var RoleService = /** @class */ (function () {
  49. function RoleService () {
  50. this.roleName = "管理员";
  51. }
  52. RoleService.prototype.DistribRoles = function (userName, isValid) {
  53. console.log("分配角色.....");
  54. };
  55. __decorate([MethodInterceptor("DistribRoles方法")],
  56. RoleService.prototype, "DistribRoles", null);
  57. return RoleService;
  58. }());
  59. // 3. 装饰器方法
  60. function MethodInterceptor (paramsValue) {
  61. console.log("方法装饰器....");
  62. return function (targetClassPrototype, methodName, methodDecri) {
  63. //targetMethodSave.value 表示原来目标类HttpClient的show()方法
  64. // 1.1 先保存目标类的方法到targetMethodSave
  65. console.log("进入方法装饰器:methodDecri:", methodDecri);
  66. var targetMethodSave = methodDecri.value;
  67. console.log("targetMethodSave:", targetMethodSave);
  68. // 1.2.让value函数建立新得函数对象空间
  69. // value建立一个新的函数后,
  70. // RoleService对象调用DistribRoles;会执行value指向的新函数
  71. // 并不会执行原来RoleService目标类中DistribRoles方法
  72. // 这里建立的一个新函数就和后端 Java的spring AOP中的方法拦截器思想就完全一样
  73. methodDecri.value = function () {
  74. var args = [];
  75. for (var _i = 0; _i < arguments.length; _i++) {
  76. args[_i] = arguments[_i];
  77. }
  78. console.log("this:", this);
  79. // 迭代所有参数
  80. args = args.map(function (arg) {
  81. if (typeof arg === "string") {
  82. return StringUtil.trimSpace(arg);
  83. }
  84. return arg;
  85. });
  86. console.log(args);
  87. // 1.4.总结:这是一种典型的用方法装饰器扩大原来方法功能的案例
  88. // 1.5 但如果增强原来方法功能后,还想继续执行原来RoleService类中DistribRoles方法
  89. // 使用apply执行targetMethodSave原来函数
  90. targetMethodSave.apply(this, args);
  91. };
  92. // 方法执行之后,继续执行后续代码
  93. console.log("methodDecri.value:");
  94. };
  95. }

:::info Object.defineProperty(target, key, targetinfo)在方法拦截器中的作用:
因为Object.getOwnPropertyDescriptor(Customer.prototype, "buy")每次获取的不是原来的prototype上的空间,而是开辟了一个新的空间。可以简单验证:重复使用该方法获取的出的对象空间不相等console.log(dataprops === dataprops2); //false
所以,需要Object.defineProperty(target, key, targetinfo)将拦截器修饰过的方法重新赋值给原来的prototype。 :::

  1. // 手动实现拦截
  2. // 该方法获取的不是实际的prototype中的对象空间,而是开辟出一个新的空间
  3. // 通过 dataprops === dataprops2 值为false即可验证。
  4. let dataprops = Object.getOwnPropertyDescriptor(Customer.prototype, "buy");
  5. let dataprops2 = Object.getOwnPropertyDescriptor(Customer.prototype, "buy");
  6. console.log(dataprops === dataprops2); //false
  7. let savedMethod = dataprops.value;
  8. dataprops.value = function (...args) {
  9. args = args.map((arg) => {
  10. if (typeof arg === "string") {
  11. return StringUtil.trimSpace(arg);
  12. }
  13. return arg;
  14. });
  15. console.log("拦截方法的前置功能args: ", args);
  16. savedMethod.call(this, args);
  17. console.log("拦截方法的后置功能args: ", args);
  18. };
  19. // 如果不加这句话,就不能实现拦截器的功能
  20. Object.defineProperty(Customer.prototype, "buy", dataprops);
  21. let cust = new Customer();
  22. cust.buy("物 资");

4. 属性装饰器

1. 属性装饰器的实现

  1. function loginProperty(attrValue: any) {
  2. return function (targetClassPrototype: any, attrName: string | symbol) {
  3. console.log("targetclassPrototype:", targetClassPrototype);
  4. console.log("attrname:", attrName);
  5. (targetClassPrototype.constructor as any).custLevelDescri = function () {
  6. console.log("消费5000元升级为贵宾");
  7. console.log("消费10000元升级为贵宾,赠送微波炉一个");
  8. };
  9. };
  10. }
  11. // 顾客目标类
  12. class CustomerService {
  13. public custname: string = "王五";
  14. @loginProperty("顾客登记")
  15. public degree!: string;
  16. constructor() {}
  17. show() {
  18. console.log("顾客名:", this.custname);
  19. }
  20. }
  21. (CustomerService as any).custLevelDescri();
  22. export {};

2. 底层JS源码

属性装饰器最终返回的结果是undefined

  1. // 1. 底层JS 组合装饰器和目标类 __decorate 函数
  2. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  3. // argsnum 参数个数
  4. var argsnum = arguments.length;
  5. // targetinfo 被装饰器修饰的目标【类或属性或方法或方法参数,本案例为类】
  6. // argsnum=2 装饰器修饰的是类或者构造器参数,targetinfo=target[类名]
  7. // argsnum=4 装饰器修饰的是方法【第四个参数desc等于null]
  8. // targetinfo=该方法的数据属性 desc = Object.getOwnPropertyDescriptor(target, key)
  9. // argsnum=3 装饰器修饰的是方法参数或者属性,targetinfo = undefined
  10. var targetinfo = argsnum < 3 ? target : desc === null ?
  11. desc = Object.getOwnPropertyDescriptor(target, key) : desc; //S100
  12. // decorator保存装饰器数组元素
  13. var decorator;
  14. // 元数据信息,支持reflect-metadata元数据
  15. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") {
  16. targetinfo = Reflect.decorate(decorators, target, key, desc);
  17. } else
  18. // 装饰器循环,倒着循环,说明同一个目标上有多个装饰器,执行顺序是倒着执行
  19. for (var i = decorators.length - 1; i >= 0; i--) {
  20. if (decorator = decorators[i]) {
  21. // 如果参数小于3【decorator为类装饰器或者构造器参数装饰器】执行decorator(targetinfo)
  22. // 直接执行decorator装饰器,并传递目标targetinfo,这里是类
  23. // 如果参数大于3【decorator为方法装饰器】
  24. // 直接执行 decorator(target, key, targetinfo)
  25. // 如果参数等于3 【decorator为方法参数装饰器或者属性装饰器】
  26. // 直接执行decorator(target, key)
  27. // targetinfo最终为各个装饰器执行后的返回值,
  28. // 但如果没有返回值,直接返回第S100行的targetinfo
  29. targetinfo = (argsnum < 3 ? decorator(targetinfo) : argsnum > 3 ?
  30. decorator(target, key, targetinfo) : decorator(target, key)) || targetinfo;
  31. console.log("targetinforesult:", targetinfo) // undefined
  32. }
  33. }
  34. // 属性装饰器最终返回的结果是undefined
  35. return argsnum > 3 && targetinfo && Object.defineProperty(target, key, targetinfo),
  36. targetinfo;
  37. }
  38. // 底层 JS 组合装饰器和目标类 __decorate 函数结束
  39. // 2. 属性装饰器
  40. function loginProperty(attrValue) {
  41. return function (targetclassPrototype, attrname) {
  42. console.log("targetclassPrototype:", targetclassPrototype);
  43. console.log("attrname:", attrname);
  44. targetclassPrototype.constructor.custLevelDescri = function () {
  45. console.log("消费5000元升级为贵宾");
  46. console.log("消费10000元升级为贵宾,赠送微波炉一个");
  47. };
  48. };
  49. }
  50. // 3.目标类
  51. var CustomerService = /** @class */ (function () {
  52. function CustomerService() {
  53. this.custname = "王五";
  54. }
  55. CustomerService.prototype.show = function () {
  56. console.log("顾客名:", this.custname);
  57. };
  58. __decorate([
  59. loginProperty("顾客登记")
  60. ], CustomerService.prototype, "degree");
  61. return CustomerService;
  62. }());
  63. CustomerService.custLevelDescri();

5. 其他装饰器

:::warning 装饰器执行顺序:
1. 属性装饰器 ==> 2. 方法参数装饰器 ==> 3. 方法装饰器 ===> 4. 构造器参数装饰器 ===> 4. 类装饰器 :::

1. 参数装饰器

  1. function UrlParam(params: any) {
  2. return function paramDecorator(
  3. targetClassPrototype: any,
  4. methodname: string,
  5. paramindex: number
  6. ) {
  7. console.log("targetClassPrototype:", targetClassPrototype);
  8. console.log("methodname:", methodname);
  9. console.log("paramindex:", paramindex);
  10. targetClassPrototype.info = params;
  11. };
  12. }
  13. class People {
  14. eat(@UrlParam("地址信息") address: string, who: string) {
  15. console.log("address:", address);
  16. }
  17. }
  18. // 执行结果
  19. targetClassPrototype: {}
  20. methodname: eat
  21. paramindex: 0

2. 构造函数参数装饰器

  1. 先安装 reflect-metadata 第三方包 【后面会有详细讲解,先简单了解即可】
  2. UserController 控制器类实现
  3. UserService 业务类实现
  4. 保存对象的集合类实现 【单件设计模式】
  5. 构造参数装饰器实现

    3. 元数据操作

    :::info 元数据
    【定义】元数据指附加在对象、类、方法、属性、参数上的数据。
    【作用】元数据用来帮助提供实现某种业务功能需要用到的数据。 :::

    1. 对象和对象属性上使用元数据

    ```typescript import ‘reflect-metadata’ // 1. 对象 let obj = { username: “罗斯福”, age: 23, info() { console.log(“信息”); } }

// 2.1 Reflect.defineMetadata 是一个重载的方法 // 定义格式 // 为类或者对象上定义元数据 Reflect.defineMetadata(metakey,metavalue,targetClassOrObject) // 为方法定义元数据 Reflect.defineMetadata(metakey,metavalue,targetprototype,methodname) // 为属性定义元数据 Reflect.defineMetadata(metakey,metavalue,targetprototype,propkey)

// 说明:打开 d.ts 定义描述文件说明:Reflect 是命名空间,defineMetadata 是命名空间中的一个方法。 // 2.2 在对象上定义元数据 Reflect.defineMetadata(‘firstdescribe’, ‘对象属性全部符合要求’, obj); Reflect.defineMetadata(‘seconddescribe’, ‘对象不可删除’, obj);

// 2.3 获取obj上metakey为 firstdescribe 的值 console.log(Reflect.getMetadata(‘firstdescribe’, obj))// 输出对象属性全部符合要求

// 2.4 获取obj上metakey不存在的值 console.log(Reflect.getMetadata(‘threedescribe’, obj))// 输出undefined

// 3 使用 Reflect.defineMetadata 在对象属性上定义元数据。 // 3.1 在对象属性上定义和获取元数据 Reflect.defineMetadata(‘usernamemetakey’, ‘用户名合法’, obj,”username”); Reflect.getMetadata(‘usernamemetakey’, obj, “username”));// 输出用户名合法

// 3.2 使用 Reflect.hasMetadata 查看对象或对象属性上是否存在某个元数据 if (Reflect.hasMetadata(‘describe’, obj)) { console.log(“obj存在describe元数据”); }

  1. <a name="sEOhi"></a>
  2. ### 2. 直接在类、方法上定义元数据
  3. ```typescript
  4. // 1. 在类上定义元数据,只是格式不同,效果与上一节的defineMetadata一样
  5. @Reflect.metadata('decribe', '都是地球人')
  6. class People {
  7. @Reflect.metadata("descible", "姓名不能包含非法汉字")
  8. username = "wangwu"
  9. @Reflect.metadata("importinfo", "去吃陶然居好吗")
  10. eat() {
  11. }
  12. }
  13. // 2 获取元数据的方法和上一节一致
  14. // 2.1 获取类上的元数据
  15. console.log(Reflect.getMetadata('decribe', People));// 都是地球人
  16. // 2.2 获取方法上的元数据 第二个参数是原型
  17. console.log(Reflect.getMetadata('importinfo', People.prototype, 'eat'));//去吃陶然居好吗
  18. // 2.3 判断People.prototype 原型上 eat 方法上是否存在importinfo元数据
  19. if (Reflect.hasMetadata('importinfo', People.prototype, 'eat')) {
  20. console.log("hasMetadata=>People原型上存在eat方法的importinfo元数据");
  21. }
  22. // 3 定义子类
  23. class ChinesePeople extends People {
  24. guoYear() {
  25. }
  26. }
  27. // 4 子类获取父类原型上的方法 ———— hasMetadata
  28. if (Reflect.hasMetadata('importinfo', ChinesePeople.prototype, 'eat')) {
  29. console.log("hasMetadata=>ChinesePeople原型上通过继承也获取到了eat方法和eat方法的importinfo元数据");
  30. }
  31. // 5 获取自有元数据,但不能获取原型链上父类的元数据 ———— hasOwnMetadata
  32. if (Reflect.hasOwnMetadata('importinfo', ChinesePeople.prototype, 'eat')) {
  33. console.log("hasOwnMetadata=>ChinesePeople原型上存在eat方法的importinfo元数据");
  34. } else {
  35. console.log("hasOwnMetadata=>ChinesePeople原型上不存在eat方法的importinfo元数据");
  36. }

3. 直接在类属性上定义元数据

  1. import 'reflect-metadata'
  2. // 为类定义元数据
  3. @Reflect.metadata("info", "地球人")
  4. class People {
  5. @Reflect.metadata('descible1', '居住地为主要城市')
  6. @Reflect.metadata('descible2', '上海')
  7. place: Array<string> = ["中国", "北京"]
  8. @Reflect.metadata('firstname', '第一个名字')
  9. @Reflect.metadata('lastname', '最后一个名字')
  10. getFullName(name: string, age: string): number {
  11. return 100
  12. }
  13. }
  14. // 获取元数据
  15. console.log(Reflect.getMetadata('info', People));//地球人
  16. console.log(Reflect.getMetadata("descible", People.prototype, 'place'));//rose
  17. console.log(Reflect.getMetadata('firstname', People.prototype, 'getFullName'))//Jim
  18. console.log(Reflect.getMetadata('lastname', People.prototype, 'getFullName'))//Jim
  19. // [
  20. // 'design:returntype',
  21. // 'design:paramtypes',
  22. // 'design:type',
  23. // 'lastname',
  24. // 'firstname'
  25. // ]
  26. // 获取People.prototype 上getFullName方法的全部元数据Key组成的数组
  27. console.log(Reflect.getMetadataKeys(People.prototype, "getFullName"));
  28. Reflect.getMetadataKeys(People.prototype).forEach((item) => {
  29. console.log("metadatakey:", item);
  30. })
  31. Reflect.getMetadataKeys(People.prototype, 'getFullName').forEach((metakey) => {
  32. console.log("11metadatakey:", metakey);
  33. console.log(Reflect.getMetadata(metakey, People.prototype, 'getFullName'));
  34. })
  35. // 获取People类上place方法的全部元数据Key组成的数组
  36. // 输出
  37. // [
  38. // 'design:type',
  39. // 'descible1',
  40. // 'descible2'
  41. // ]
  42. console.log(Reflect.getMetadataKeys(People.prototype, "place"));
  43. Reflect.getMetadataKeys(People.prototype, 'place').forEach((metakey) => {
  44. console.log("属性metadatakey:", metakey);
  45. console.log(Reflect.getMetadata(metakey, People.prototype, 'place'));
  46. })
  47. class ChinesePeople extends People {
  48. @Reflect.metadata("descible", "姓名不能包含非法汉字")
  49. guoYear(args: string) {
  50. }
  51. }
  52. console.log("getMetadataKeys==>查看父类上的方法...");
  53. console.log(Reflect.getMetadataKeys(ChinesePeople.prototype, 'getFullName'))//Jim
  54. console.log("getOwnMetadataKeys不能查看父类上的方法...");
  55. console.log(Reflect.getOwnMetadataKeys(ChinesePeople.prototype, 'getFullName'))//Jim

4. 3个重要且特殊的内置元数据key

:::success

  1. design:paramtypes
    1. 构造器所有参数数据类型组成的数组
    2. 类中方法全部参数的数据类型组成的数组
  2. design:type
    1. 获取类属性的数据类型
    2. 获取类方法参数的数据类型
  3. design:returntype
    1. 获取类方法返回值的数据类型 :::

      6. 仿Nest.js装饰器

      1. 涉及的专业术语

      :::info
  • @Controller控制器装饰器,是用来支持页面的各种请求的类的装饰器
  • @Service业务逻辑层类装饰器
  • @Autowired自动装配,一般是把外部其他数据注入给当前属性或方法参数的装饰器
  • dependencyid一个唯一标识符变量,作为@Autowired的实参,使用@Autowired为不同类属性或方法参数注入数据时,dependencyid用于区别这些不同的类
  • singleton标注是否是单列注入的参数,可选
  • target表示被注入的目标类 :::

    2. 依赖注入

    :::success 【依赖注入的特点】创建和使用分离,外部给内部的属性赋值。
    【好处】让项目在日后修改和变动时,不修改或者少量修改代码即可实现功能,大大提高了项目的可扩展性。 :::

    1. 初步实现

    实现步骤:
  1. 建立伪接口类UserServiceInter
  2. 修改UserService的名字为UserServiceImpl
  3. 修改自动装配装饰器@Autowired代码

    1. import UserServiceImpl from "./UserServiceImpl";
    2. // 伪接口
    3. export default class UserServiceInter {
    4. public static getServiceImplClass() {
    5. return UserServiceImpl;
    6. }
    7. }
    1. export default class UserServiceImpl {
    2. constructor() {
    3. console.log("UserServiceImpl construct");
    4. }
    5. login(username: string, pwd: string, role: string) {
    6. console.log("进入service ...Login,username:", username);
    7. if (username === "admin" && pwd === "123" && role === "admin") {
    8. return true;
    9. } else {
    10. return false;
    11. }
    12. }
    13. register() {
    14. console.log("usersevice...register");
    15. }
    16. }

    ```typescript import “reflect-metadata”;

export default function Autowired(injectid: string): PropertyDecorator { return (targetClassPrototype, propertyKey) => { // PropClass=UserServiceInter伪接口类 let PropServiceClass = Reflect.getMetadata( “design:type”, targetClassPrototype, propertyKey ); let PropServiceImplClass = PropServiceClass.getServiceImplClass(); let PropServiceImplClassObj = new PropServiceImplClass(); Reflect.defineProperty(targetClassPrototype, propertyKey, { value: PropServiceImplClassObj, });

  1. // 方法一: collection
  2. // collectionInstance.set(propertyKey, PropClassObj);
  3. // 方法二: Object.defineProperty
  4. // 好处:由于targetClassPrototype原型+propertyKey绝对是不会被覆盖的
  5. // 充分保证了数据属性中的value的对象的唯一性

}; }

  1. ```typescript
  2. import "reflect-metadata";
  3. import Autowired from "../decorator/autowiredDecortator";
  4. import UserServiceImpl from "../service/UserServiceImpl";
  5. import UserServiceInter from "../service/UserServiceInter";
  6. class UserController {
  7. @Autowired("userService") // 修改Inject为更专业的Autowired单词
  8. private userServiceImpl!: UserServiceInter;
  9. public login(): void {
  10. let userServiceImpl: UserServiceImpl = Reflect.getOwnPropertyDescriptor(
  11. UserController.prototype,
  12. "userServiceImpl"
  13. ).value;
  14. userServiceImpl.register();
  15. (this.userServiceImpl as UserServiceImpl).register();
  16. }
  17. }
  18. let controller = new UserController();
  19. controller.login();
  20. export {};

3. 复杂泛型-param参数的处理

:::info express中可以自动实现param参数的识别,可以通过ts类型处理得到。
例如 type Param = RouteParameters<”/showFood/:foodname/:price”> = { foodname : string } & { price : string } ::: RouteParameters的实现方式如下:

  1. 实现RemoveTail类型,可以移除字符串中后半部分,使用通配符可以实现移除指定类型的内容。
  2. 通过多次嵌套RemoveTail类型,得到GetRouteParameter类型。GetRouteParameter的作用就是获取第一个/前,排除.-影响的参数的类型。
  3. 基于GetRouteParameter,就可以实现最终的RouteParameters ``typescript type RemoveTail<S extends string, Tail extends string> = S extends${infer P}${Tail}` ? P : S;

let result: RemoveTail<”/showFood/:foodname/:price”, “/:foodname/:price”>; // result: “/showFood”

// 中,遇到第一个匹配/的位置就停止, 例如 let result2: RemoveTail<”:foodname.beijing-china/:price/:shopname”, /${string}>; // result2: “:foodname.beijing-china”

type GetRouteParameter = RemoveTail, -${string}>,.${string}>;

let result3: GetRouteParameter<”:foodname.beijing-china/:price/:shopname”>; // result3: “:foodname”

  1. ```typescript
  2. export type RouteParameters<Route extends string> = string extends Route
  3. ? ParamsDictionary
  4. : Route extends `${string}(${string}`
  5. ? ParamsDictionary
  6. : Route extends `${string}:${infer Rest}`
  7. ? (GetRouteParameter<Rest> extends never
  8. ? ParamsDictionary
  9. : GetRouteParameter<Rest> extends `${infer ParamName}?`
  10. ? { [P in ParamName]?: string }
  11. : { [P in GetRouteParameter<Rest>]: string }) &
  12. (Rest extends `${GetRouteParameter<Rest>}${infer Next}` ? RouteParameters<Next> : unknown)
  13. : {};
  14. type resultType = RouteParameters<"/:foodname.beijing-china/:price/:shopname">;
  15. // { foodname: string } & { price: string } & { shopname: string };