Class Decorator
Decorator(装饰器)
ClassDecorator(类装饰器)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| const Doc: ClassDecorator = (target) => { console.log(target)
target.prototype._name = 'Luffy' }
@Doc class demo() { constructor() {} }
const Xiaoming = new demo()
console.log(Xiaoming._name)
|
PropertyDecorator(属性装饰器)
| const Doc: PropertyDecorator = (target: Object, propertyKey: string | symbol) => { console.log(target, propertyKey) }
class demo() { @Doc public name: string constructor() { this.name = 'Luffy' } }
|
MethodDecorator(方法装饰器)
| const Doc: MethodDecorator = (target: Object, propertyKey: string | symbol, descriptor: any) => { console.log(target, propertyKey, descriptor) }
class demo() { constructor() {}
@Doc getAll() {} }
|
MethodDecorator(参数装饰器)
| const Doc: ParameterDecorator = (target: Object, propertyKey: string | symbol, index: number) => { console.log(target, propertyKey, index) }
class demo() { constructor() {}
getAll(name: string, @Doc age: string) {} }
|
使用装饰器实现一个get请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| const Get = (url: string) => { return (target: Object, propertyKey: string | symbol, descriptor: any) => { const fnc = descriptor.value; axios.get(url).then(res => { fnc(res, { status: 200, success: true }) }).catch(e => { fnc(res, { status: 500, success: false }) }) } }
class user { constructor() {}
@Get('请求地址') getAll(res: any, status: any) { console.error(res, status) } }
|