装饰器基础

装饰器基础- typescript

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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import "reflect-metadata";

// 基础
@Reflect.metadata("class", "value_test")
class Test {

@Reflect.metadata("field", "value_name")
name = "dottie";

@Reflect.metadata('method', "value_hi")
hi(): string {
return 'hi, today!'
}
}

console.log(Reflect.getMetadata('class', Test)); // value_test
console.log(Reflect.getMetadata('field', Test.prototype, 'name')); // value_name
console.log(Reflect.getMetadata('method', Test.prototype, "hi")); // value_hi

// 获取类型信息,返回值,参数等信息
function PropDeco(): PropertyDecorator {
return (target: any, key: any) => {
console.log(target); // SomeClass {}
const type = Reflect.getMetadata("design:type", target, key);
console.log(type.name); // String
}
}

class SomeClass {
@PropDeco()
public name!: string;
}

// 自定义 metadatakey
function Component(value?: string): ClassDecorator {
return (target: any) => {
Reflect.defineMetadata("component", value, target);
}
}

function Resource(value?: string): PropertyDecorator {
return (target: any, key: any) => {
Reflect.defineMetadata("field", value, target, key);
}
}

function Method(): MethodDecorator {
return (target: any, key: any, descriptor: any) => {
Reflect.defineMetadata('method', descriptor.value, target, key);
}
}

@Component("app")
class TestClass {
@Resource("这是姓名")
public name!: string;

@Method()
public hi():String {
return "hi!";
}
}

const cValue = Reflect.getMetadata('component', TestClass);
console.log(cValue); // app
const fValue = Reflect.getMetadata('field', TestClass.prototype, 'name');
console.log(fValue); // 这是姓名
const mValue = Reflect.getMetadata('method', TestClass.prototype, "hi");
console.log(mValue); // [Function]
console.log(mValue.call(null)) // hi!