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
至此,结束。