TypeScript: 类的装饰器(二)

类的装饰器执行时机

接上文,我们引出了 TypeScript 类的装饰器后,接下来,去挖掘下它的特性

PS:上文,TypeScript: 类的装饰器(一)

先写一小段类的装饰器的代码:

function addDecorator(constructor: any) {
  console.log("add decorator");
}

@addDecorator
class Test {}

const t: Test = new Test();

此时运行:npm run dev

那么,我们在加多一个Test的实例:

function addDecorator(constructor: any) {
  console.log("add decorator");
}

@addDecorator
class Test {}

const t: Test = new Test();
const t1: Test = new Test();

此时运行:npm run dev


是不是,类的装饰器只会在第一个实例化后执行一次?我们把Test类的实例去掉,代码变为如下:

function addDecorator(constructor: any) {
  console.log("add decorator");
}

@addDecorator
class Test {}

此时运行:npm run dev


由此可见,类的装饰器执行和实例化无关,它在程序编译的时候就运行了

类的装饰器执行顺序

我们再加一个装饰器,代码变为如下:

function addDecorator(constructor: any) {
  console.log("add decorator");
}

function addNextDecorator(constructor: any) {
  console.log("add next decorator");
}

@addDecorator
@addNextDecorator
class Test {}

此时运行:npm run dev

由此可见,多个类的装饰器执行顺序是由下到上,或着说离类最近的装饰器最先执行
原文链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值