类的装饰器

本篇文章将介绍TypeScript中类的装饰器。

可以把类的装饰器看成是一个函数,通过装饰器可以对一个类添加额外的信息(属性、方法)。

定义装饰器

定义方法,接收类的构造函数为参数。

function testDecorator(constructor: any) {
    console.log('testDecorator')
}
使用装饰器

使用装饰器很简单,在类上面使用@符添加装饰器注解就可以了。

@testDecorator
class Test{}
运行时机

装饰器的运行时机是类创建后立即执行。

修改类行为

通过在装饰器方法中,对类的构造函数添加自定义方法实现修改类行为。

function testDecorator(constructor: any) {
  constructor.prototype.getName = () => {
    console.log('testDecorator')
  }
}

@testDecorator
class Test{}
const test = new Test();
(test as any).getName() 
多个装饰器的调用流程

如果注册了多个装饰器,那么执行流程是从下到上,先注册的后执行。

装饰器进阶

函数返回不同类型的装饰器。


function testDecorator(flag: boolean) {
  if (flag) {
    return function(constructor: any) {
      constructor.prototype.getName = () => {
        console.log('testDecorator')
      }
    }
  } else {
    return function (constructor: any) { }
  }
}

@testDecorator(true)
class Test{
}
const test = new Test();
(test as any).getName()
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值