前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >typescript笔记3装饰器

typescript笔记3装饰器

作者头像
路过君
发布2022-04-13 13:48:31
2290
发布2022-04-13 13:48:31
举报
文章被收录于专栏:路过君BLOG from CSDN

类装饰器

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

代码语言:javascript
复制
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('类装饰器动态方法')
        }
    }
}

属性装饰器

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

方法装饰器

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

代码语言:javascript
复制
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]) // 修改原始方法参数
        }
    }
}

方法参数装饰器

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

代码语言:javascript
复制
function argumentDecorator(value: string) {
    return function (
        target: any,
        method: any, // 方法名称
        argIndex: any // 参数索引
    ) {
        console.log(value, target, method, argIndex)
    }
}

使用样例

代码语言:javascript
复制
@classDecorator('类装饰器')
class MyClass {
    @propDecorator('属性装饰器')
    prop: string | undefined

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

    constructor() {
    }
}

执行顺序

  1. 属性
  2. 方法
  3. 方法参数
  4. 类 多个同级装饰器,从后向前执行
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022/03/22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 类装饰器
  • 属性装饰器
  • 方法装饰器
  • 方法参数装饰器
  • 使用样例
  • 执行顺序
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档