zoukankan      html  css  js  c++  java
  • 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 报错

  • 相关阅读:
    larbin结构分析
    《钱不要存银行》OneNote
    全局变量、extern/static/const区别与联系
    GIS网址,转自别处
    MSDN无法显示页面的解决
    人生没有奇迹
    开源GIS系统
    推荐:GDAL学习资源
    中国农科院资源区划所MODIS的遥感信息地面接收站
    泡沫产生的特点
  • 原文地址:https://www.cnblogs.com/wzndkj/p/13401779.html
Copyright © 2011-2022 走看看