ES7 装饰器使用示例

ES7 装饰器使用示例

示例代码:

// ts 装饰器

// 类装饰器
function aClass(target: any): void {
    // target 为当前装饰的类
    target.prototype.name = '动态扩展的属性'
    target.prototype.run = () => {
        console.log('2.动态扩展的方法')
    }
}

// 类装饰器(带参数)
function bClass(name: string): Function {
    return function(target: any) {
        console.log('1.' + name)
        target.prototype.name = name
    }
}

// 类装饰器
function cClass(target: any): any {
    return class extends target {
        url: string = '//proxy.xxx'
    }
}

// 属性装饰器
function aProperty(params: any) {
    return function(target: any, attr: any) {
        // 执行在被装饰的类的构造方法之前
        target[attr] = params
    }
}

// 方法装饰器
function get(params: any) {
    return function(target: any, methodName: any, desc: any) {
        var oMethod = desc.value
        desc.value = function(...args: any[]) {
            // ...something other
            return oMethod.apply(this, args)
        }
    }
}

// 方法参数装饰器(不常用)
function logParams(params: any) {
    return function(target: any, methodName: any, paramsIndex: any) {
        target.fullUrl = params + ':' + target.url
    }
}

@aClass
@bClass('工厂装饰器')
@cClass
class HttpClinet {
    @aProperty('//adapter.xxx')
    public url: string
    constructor() {
        this.url = '//api.xxx'
    }
    @get('//get')
    getUrl(@logParams('https') ...args: any) {
        console.log('3.' + JSON.stringify(args))
        return this.url
    }
}

const h: any = new HttpClinet()
h.run()
console.log('4.' + h.getUrl('http'))
console.log('5.' + h.fullUrl)

node 执行ts 转换后的代码,结果:

1.工厂装饰器
2.动态扩展的方法
3.["http"]
4.//proxy.xxx
5.https://adapter.xxx

至此,结束。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值