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 报错

  • 相关阅读:
    科研:保持开放的心灵
    jquary实现轮播图(省略了css样式)
    Django实现注册/登录:方法2
    Django实现注册/登录:方法1
    卸载MySQL出现2503,2502解决方法
    安装MySQL出现2503,2502错误解决方法
    Markdown数学公式
    Linux安装Oracle11.2.0数据库
    Python列表生成式
    R语言apply()函数用法
  • 原文地址:https://www.cnblogs.com/wzndkj/p/13401779.html
Copyright © 2011-2022 走看看