本文详细介绍了装饰器在JavaScript中的应用,涵盖类装饰器、属性装饰器、参数装饰器和方法装饰器,通过实例展示如何使用并理解这些高级特性。
什么是装饰器
装饰器是一种特殊的类型声明,他可以附加在类,方法,属性,参数上面。
装饰器写法 tips(需要开启一项配置)
需要在tsconfig.json中开启experimentalDecorators
1// tsconfig.json
2{
3 "compilerOptions": {
4 "experimentalDecorators": true,
5 }
6}
类装饰器
主要是通过@符号添加装饰器,他会自动把class的构造函数传入到装饰器的第一个参数 target
然后通过prototype可以自定义添加属性和方法
1function decotators (target:any) {
2 target.prototype.name = '小满'
3}
4
5
6// 本质就是: 把类对象放到 decorator 函数里面执行一次
7@decotators
8class Xiaoman {
9
10 constructor () {
11
12 }
13
14}
15
16const xiaoman:any = new Xiaoman()
17
18console.log(xiaoman.name)
属性装饰器
同样使用@符号给属性添加装饰器
他会返回两个参数
1.原形对象
2.属性的名称
1const currency: PropertyDecorator = (target: any, key: string | symbol) => {
2 console.log(target, key)
3}
4
5
6class Xiaoman {
7 @currency
8 public name: string
9 constructor() {
10 this.name = ''
11 }
12 getName() {
13 return this.name
14 }
15}
参数装饰器
同样使用@符号给属性添加装饰器
他会返回三个参数
1.原形对象
2.方法的名称
3.参数的位置从0开始
1const currency: ParameterDecorator = (target: any, key: string | symbol,index:number) => {
2 console.log(target, key,index)
3}
4
5
6class Xiaoman {
7 public name: string
8 constructor() {
9 this.name = ''
10 }
11 getName(name:string,@currency age:number) {
12 return this.name
13 }
14}
方法装饰器
同样使用@符号给属性添加装饰器
他会返回三个参数
1.原形对象
2.方法的名称
3.属性描述符 可写对应writable,可枚举对应enumerable,可配置对应configurable
1const currency: MethodDecorator = (target: any, key: string | symbol,descriptor:any) => {
2 console.log(target, key,descriptor)
3}
4
5
6class Xiaoman {
7 public name: string
8 constructor() {
9 this.name = ''
10 }
11 @currency
12 getName(name:string,age:number) {
13 return this.name
14 }
15}