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();

打印结果:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_39111074/article/details/132167256