Nestjs
yatbfm

装饰器

类装饰器

类装饰器可以修饰类,给类添加属性、增加构造函数的执行等。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* constructor 参数为为被装饰的类的构造函数
*/
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
/**
* @param target 目标对象,如果是静态成员,则是类的构造函数;如果是实例成员,则是类的原型对象
* @param propertyKey 成员名称
* @param descriptor 成员属性描述符
*/
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);
}
}
由 Hexo 驱动 & 主题 Keep
访客数 访问量