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

猜你喜欢

转载自www.cnblogs.com/wzndkj/p/13401779.html