• TypeScript 类的装饰器


    // 类的装饰器:对类的一个修饰
    
    /**
    * 装饰器本身是一个函数
    * @param constructor
    * 类的装饰器接收的函数是类的构造函数 constructor
    *
    * testDecorator 的运行时机是类创建的时候立即执行
    * 对类做修饰,不是对实例做修饰
    */
    function testDecorator(constructor: any) {
      constructor.prototype.getName = () => {
        console.log('dell');
      }
      console.log('decorator');
    }
    // 装饰器可以写多个
    function testDecorator1(constructor: any) {
      console.log('decorator1');
    }
    
    
    /**
    * 装饰器通过 @ 符号来使用
    * 如果报错,不支持使用,打开 tsconfig.json 这两个配置项
    * experimentalDecorators,emitDecoratorMetadata
    *
    * 多个装饰器的时候,执行的时候是从下到上,从右到左
    */
    @testDecorator @testDecorator1
    class Test{ }
    
    const test = new Test();
    (test as any).getName();




    有的时候我希望去使用 testDecorator 对类装饰,有的时候不希望对类装饰
    // 最外层是个函数,再返回一个新的函数
    function testDecorator(flag: boolean) {
      if (flag) {
        return function (constructor: any) {
          constructor.prototype.getName = () => {
            console.log('dell');
          }
        }
      } else {
        return function (constructor: any) { }
      }
    }
    
    // 执行下这个函数,跟上面不包含的效果是一样 的
    @testDecorator(true)
    class Test{ }
    
    const test = new Test();
    (test as any).getName();

    传 true ,会调用类的装饰器,传 false 报错

  • 相关阅读:
    linux 树型显示文件 tree ls tree 命令
    Linux常用命令大全
    My kingdom for a good timer! 规格严格
    org.dom4j.DocumentException: no protocol 规格严格
    利用GetObject("WinMgmts:")获取系统信息 规格严格
    给力URL 规格严格
    几个Servlet小Sample网站 规格严格
    使用SQL PLUS生成报表 规格严格
    High Resolution Timer in Java 5 规格严格
    GC调优文章精选:逐步添加 规格严格
  • 原文地址:https://www.cnblogs.com/wzndkj/p/13401779.html
Copyright © 2020-2023  润新知