装饰器初探
typescript新增了装饰器语法,不过一直处于试验阶段,需要配置tsconfig.json才能支持
添加如下代码
{ "compilerOptions": { "experimentalDecorators": true } }
利用装饰器,可以实现面向切面编程(AOP),例如常见的日志,打点上报,resful接口注解等。在不侵入业务代码的情况下,增强代码,算是一种元编程吧
如下代码,可在代码中注入日志,记录函数执行过程中的一些log
function classDecorator<T extends { new(...args: any[]): {} }>(constructor: T) { return class extends constructor { newProperty = "new property"; hello = "override"; } } function post(method: string, params: Record<string, any>) { return (target: any, key: any) => { const oldFn = target[key]; target[key] = (...args: any[]) => { console.log('---before call---'); oldFn.apply(target, args.concat(method, params)) console.log('---after call---'); } } } @classDecorator class Greeter { property = "property"; hello: string; constructor(m: string) { this.hello = m; } @post('/add', { name: 'tian', age: 23 }) say(...arg: any[]) { console.log(...arg); } } const greeter = new Greeter("world"); greeter.say(1111); console.log(greeter);
结果如下