Typescript的装饰器

装饰器(Decorator)模式 的定义:指在不改变现有对象结构的情况下,动态地给该对象增加一些职责(即增加其额外功能)的模式,它属于对象结构型模式。

函数装饰器

1
2
3
4
5
6
7
8
9

function sayGood(sayThing: ()=> void): (msg: string)=>void{
return function (msg: string){
console.log('say good' + msg);
sayThing();
}
}

sayGood(()=>{console.log('hello boy')})('candy');

类装饰器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function age(target: Function) {
target.prototype.sayName = function() {
console.log("hello jonny");
};
}

@age
class Login {
public username: string = "";
public password: string = "";
}

const login: any = new Login();
login.sayName(); //"hello jonny"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function setAge(param: string) {
return function(target: any) {
target.prototype.sayName = function() {
console.log(param);
};
};
}

@setAge("Hello Candy!")
class Login {
public username: string = "";
public password: string = "";
}

const login: any = new Login();
login.sayName(); //'hello candy'

属性装饰器

1
2
3
4
5
6
7
8
9
10
11
12
function hName(param: string) {
return function(target: any, propertyName: string) {
target[propertyName] = param;
};
}

class Hello {
@hName("Jonny")
name: string;
}

console.log(new Hello().name); // 输出: Jonny

方法装饰器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function GET(url: string) {
return function(target, methodName: string, descriptor: PropertyDescriptor) {
target.run = function() {
console.log("ok");
descriptor.value();
};
};
}

class HelloService {
constructor() {}
@GET("xx")
getUser() {
console.log("no");
}
}

const instance: any = new HelloService();

instance.run(); //ok,no

参数装饰器

1
2
3
4
5
6
7
8
9
10
11
12
13
14

function PathParam(paramName: string) {
return function(target, methodName: string, paramIndex: number) {
!target.$Meta && (target.$Meta = {});
target.$Meta[paramIndex] = paramName;
};
}

class HelloService {
constructor() {}
getUser(@PathParam("userId") userId: string) {}
}

console.log((<any>HelloService).prototype.$Meta); // {'0':'userId'}