装饰器
类装饰器
类装饰器可以修饰类,给类添加属性、增加构造函数的执行等。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
function AddAge(constructor: Function) { return class extends constructor { age: number = 15; constructor(...args) { super(...args); } }; } @AddAge class Person { constructor(name: string) {} }
|
方法装饰器
方法装饰器的方法签名:(target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor) => void | PropertyDescriptor
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
function Log( target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor ) { const originalMethod = descriptor.value; descriptor.value = function (...args) { const result = originalMethod.apply(this, args); return result; }; return descriptor; }
function Cache( target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor ) { const originalMethod = descriptor.value; const cacheMap = new Map<string, any>(); descriptor.value = function (...args) { const key = JSON.stringify(args); if (cacheMap.has(key)) { return cacheMap.get(key); } const result = originalMethod.apply(this, args); cacheMap.set(key, result); return result; }; }
class Calculator { @Log add(a: number, b: number) { return a + b; } @Cache fac(n: number) { if (n === 0) return 1; return n * fac(n - 1); } }
|