typescript笔记3装饰器

类装饰器

应用于类构造函数,用于监视,修改或替换类定义

function classDecorator2(target: any) {    // target接受被装饰的类
    target.prototype.dynamicProp = '类装饰器' //动态扩展属性
    target.prototype.dynamicMethod = function () {
        // 动态扩展方法
        console.log('类装饰器动态方法')
    }
    // 扩展替换类定义
    // return class extends target {
    //     prop: string | undefined
    //
    //     run() {
    //         super.run()
    //     }
    //
    //     dynamicProp2: string = '类装饰器扩展属性2'
    // }
}

// 装饰器工厂写法
function classDecorator(params: string) { // 可以接受装饰器传入参数
    return function (target: any) {
        target.prototype.dynamicProp = params
        target.prototype.dynamicMethod = function () {
            // 动态扩展方法
            console.log('类装饰器动态方法')
        }
    }
}

属性装饰器

function propDecorator(value: string) {
    return function (
        target: any,// 接受被装饰的类,静态成员时获得类构造函数,实例成员时获得类的原型对象
        attr: any// 接受被装饰的类和属性名称
    ) {
        target[attr] = value
    }
}

方法装饰器

应用到方法属性描述符上,用来监视,修改或替换方法定义

function methodDecorator(value: string) {
    return function (
        target: any,// 接受被装饰的类,静态成员时获得类构造函数,实例成员时获得类的原型对象
        method: any,// 接受被装饰的类和方法名称
        desc: any //成员属性描述符
    ) {
        console.log(value, desc)
        // 方法装饰器 [{
        //     value: [Function: run],
        //     writable: true,
        //     enumerable: false,
        //     configurable: true
        // }
        let originMethod = desc.value // 原始方法
        desc.value = function (arg: number) {
            console.log('修改装饰器方法', arg)
            originMethod.apply(this, [arg]) // 修改原始方法参数
        }
    }
}

方法参数装饰器

运行时被当作函数调用,可以用于为类的原型增加一些元素数据

function argumentDecorator(value: string) {
    return function (
        target: any,
        method: any, // 方法名称
        argIndex: any // 参数索引
    ) {
        console.log(value, target, method, argIndex)
    }
}

使用样例

@classDecorator('类装饰器')
class MyClass {
    @propDecorator('属性装饰器')
    prop: string | undefined

    @methodDecorator('方法装饰器')
    run(@argumentDecorator('方法参数装饰器')...args: any[]) {
        console.log('原始方法', args, arguments)
    }

    constructor() {
    }
}

执行顺序

  1. 属性
  2. 方法
  3. 方法参数

  4. 多个同级装饰器,从后向前执行

posted on 2022-04-11 22:37  路过君  阅读(2)  评论(0编辑  收藏  举报

导航