装饰器是一种特殊的类型声明,他可以附加在类,方法,属性,参数上面。
装饰器可以不修改原有代码,动态添加功能,提高代码复用性。

同一件装饰器可以给不同函数用,同一个函数也可以叠加多个装饰器。

常见使用场景:

  1. 日志记录:自动记录函数被调用了多少次
  2. 权限校验:在执行函数前先检查是否登录
  3. 计时功能:自动计算函数运行时间
  4. 网络重试:失败时自动重试 3 次

ts 使用装饰器需要在 tsconfig.json 中配置 "experimentalDecorators": true
在函数前添加@,可作为装饰器使用。

类装饰器

他会自动把 class 的构造函数传入到装饰器的第一个参数 target,
然后通过 prototype 可以自定义添加属性和方法

function decotators (target:any) {
    target.prototype.name = '路人'
}
 
@decotators
class User {
    constructor () {
 
    }
}
 
const user:any = new User()
console.log(user.name) // 路人

属性装饰器

const currency: PropertyDecorator = (target: any, key: string | symbol) => {
    console.log(target, key) // target: 原形对象, key: 属性的名称
}

class User {
    @currency
    public name: string
    constructor() {
        this.name = ''
    }
    getName() {
        return this.name
    }
}
// 会打印 {} name

参数装饰器

    const currency: ParameterDecorator = (target: any, key: string | symbol,index:number) => {
        console.log(target, key, index) // target: 原形对象, key: 方法的名称,index:参数的位置(从0开始)
    }

    class User {
        public name: string
        constructor() {
            this.name = ''
        }
        getName(name:string,@currency age:number) {
            return this.name
        }
    }

方法装饰器

    const currency: MethodDecorator = (target: any, key: string | symbol, descriptor:any) => {
        console.log(target, key, descriptor) // target: 原形对象, key: 方法的名称, descriptor:属性描述符
        // descriptor:{ value: [Function: getName], writable: true, enumrable: false, configurable: true }
    }

    class User {
        public name: string
        constructor() {
            this.name = ''
        }
        @currency
        getName(name:string,age:number) {
            return this.name
        }
    }
Last Updated:
Contributors: haizhiguang