03_装饰器

简介: 03_装饰器

这里的装饰器直接上代码了,如果是零基础请看TypeScript笔记中的“装饰器”章节

// 普通类装饰器(不可传参)
const doc: ClassDecorator = (target: any) => {
  console.log(target)
}
@doc
class Xiaoman {
  constructor() {}
}
// 类工厂装饰器(可自由传参)
const docs = (str: string): ClassDecorator => {
  return (target: any): void => {
    console.log(str)
  }
}
@docs('这是一段字符串')
class XiaomanFactory {
  constructor() {}
}
// 属性装饰器(返回构造函数和属性名)
const props: PropertyDecorator = (target: any, key: string | symbol) => {
  console.log(target, key)
}
class XiaomanProperty {
  @props
  public name: string
  constructor() {
    this.name = '小满'
  }
}
// 方法装饰器(返回构造函数、方法名和方法定义)
const method:MethodDecorator = (target: any, propertyKey: string | symbol,descriptor:any) => {
  console.log(target,propertyKey,descriptor);
}
class XiaomanMethod {
  constructor(){}
  @method
  getName(){}
}
// 参数装饰器(返回构造函数、参数名和参数所在位置(从前往后递减))
const param:ParameterDecorator = (target:any,propertyKey: string | symbol,parameterIndex: number) => {
  console.log(target,propertyKey,parameterIndex)
}
class XiaomanParams {
  constructor(){}
  myMethod(@param data:any,@param key:any){}
}
// 装饰器底层实现
class CustomXiaoman {
  constructor(){}
}
const custom = (target:any) => {
  console.log(target)
}
custom(CustomXiaoman)
目录
打赏
0
1
1
0
333
分享
相关文章
装饰器
【8月更文挑战第1天】
33 2
装饰器的实际应用
使用装饰器模式改造slf4j打印json格式日志
782 0
装饰器的实际应用
你以为装饰器那么容易学吗?
最近在使用mobx的时候考虑到每个action都要各种try...catch,各种toast loading,觉得好烦,然后想到ES7的装饰器不就是为了少写代码的吗?于是我就立马付诸实践,开始我的装饰器的第一个应用,结果踩了好多坑,瞬间感觉说的跟做得果然不一样!
1346 0
装饰器:装饰器为主,闭包和高阶函数为辅
装饰器:装饰器为主,闭包和高阶函数为辅

热门文章

最新文章

AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等