typescript-装饰器

有的时候,需要对类或方法等进行一些操作,但是不想改变原有代码结构,可以尝试添加装饰器

可以使用多个装饰器 修饰同一个类、方法、、、

装饰器格式(方法 + @方法名)

先定义一个方法作为装饰器,然后在需要使用的地方引用该装饰器,引用方法:@方法名

装饰器分类

装饰器有:类装饰器、方法装饰器、参数装饰器、属性装饰器

typescript类型:
类装饰器 - - - ClassDecorator
方法装饰器 - - - MethodDecorator
参数装饰器 - - - ParameterDecorator
属性装饰器 - - - PropertyDecorator

类装饰器 - - - ClassDecorator

接收一个参数,类函数

格式:

// 类装饰器 - - - ClassDecorator
const 装饰器名:ClassDecorator = (target) => {

}

@装饰器名
class 类名 {

}

代码示例:

const TestClassDecorator:ClassDecorator = (target) => {
  target.prototype.name = '史迪仔'
  target.prototype.fn = () => {
    console.log('今天也是元气满满的一天~');
  }
}

const Start:ClassDecorator = (target) => {
  target.prototype.start = () => {
    console.log('早上好,新的一天开始啦~');
  }
}

const End:ClassDecorator = (target) => {
  target.prototype.end = () => {
    console.log('一天结束啦,晚安,好梦~');
  }
}

@Start
@TestClassDecorator
@End
class Test {

}

const t = new Test() as any
t.start()
console.log(t.name);
t.fn();
t.end()

打印结果:
在这里插入图片描述

方法装饰器 - - - MethodDecorator

接收三个参数:类函数、方法名、成员属性描述符

格式:

 // 方法装饰器 - - - MethodDecorator
const 装饰器名:MethodDecorator = (target, propertyKey, descriptor) => {

}

class 类名 {
   @装饰器名
   方法名() {
    
   }
}

代码示例:

const Test:MethodDecorator = (target, key, des) => {
  console.log(target, key, des);
  console.log('我是一个方法装饰器');
  
}

class Student {

  @Test
  getData() {
    
  }

}

const s = new Student()
s.getData();

打印结果:
在这里插入图片描述

参数装饰器 - - - ParameterDecorator

接收三个参数:类的构造函数、方法名、该参数在方法形参中的位置索引值

格式:

// 参数装饰器 - - - ParameterDecorator
const 装饰器名:ParameterDecorator = (target: any, propertyKey: string, paramIndex: number) => {

}


class 类名 {
	方法名(@装饰器名 参数名) {
    
   }
}

属性装饰器 - - - PropertyDecorator

接收两个参数:类的构造函数、属性名

格式:

// 属性装饰器 - - - PropertyDecorator
const 装饰器名:PropertyDecorator = (target: Object, propertyKey: string) => {

}

class 类名 {
	@装饰器名
	属性名:属性类型 = 属性值
}

装饰器工厂

有的时候,希望给装饰器传参,根据传入的参数进行一些操作,可以尝试装饰器工厂(定义一个可以接收参数的函数,函数内部再返回装饰器)

格式:

const 方法名 = (参数名) => {
  const 装饰器名:ClassDecorator = (target) => {
    // 一些操作
  }
  return fn装饰器名
}

@方法名('参数值')
class 类名 {

}

代码示例:

const Base = (val) => {
  const fn:ClassDecorator = (target) => {
    target.prototype.name = val
    target.prototype.like = '吃竹子'
    target.prototype.say = () => {
      console.log('请叫我果赖~');
    }
  }
  return fn
}

@Base('花花')
class Animal {

}

const a = new Animal() as any
console.log(a.name);
console.log(a.like);
a.say();

打印结果:

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值