类装饰器
typescript
/**
* @param target: 类的构造函数
*/
function addAge(target: Function) {
target.prototype.age = 18;
}
@addAge
class Persons {
name: string;
age!: number;
constructor() {
this.name = 'Richard';
}
}
let persons = new Persons();
console.log(persons.age); // 18
方法装饰器
typescript
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
@enumerable(false)
greet() {
return 'Hello, ' + this.greeting;
}
}
/**
* @param value: 装饰器调用时传入的参数
*/
function enumerable(value: boolean) {
/**
* @target: 对于静态成员来说是类的构造函数,对于实例成员是类的原型对象。
* @propertyKey: 成员的名字
* @descriptor: 成员的属性描述符
*/
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
console.log(descriptor.value);
};
}
属性装饰器
typescript
/**
* @param target: 对于静态成员来说是类的构造函数,对于实例成员是类的原型对象
* @param name: 成员的名字
*/
function attr(target: object, name: string) {
console.log(target);
console.log(name);
}
class Persons {
@attr
name: string;
constructor() {
this.name = 'Richard';
}
}
let persons = new Persons();
参数装饰器
typescript
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet(@required name: string) {
return 'Hello ' + name + ', ' + this.greeting;
}
}
/**
* @param target: 对于静态成员来说是类的构造函数,对于实例成员是类的原型对象
* @param name: 成员的名字
* @param index: 参数在函数参数列表中的索引
*/
function required(target: object, name: string, index: number) {
console.log(target);
console.log(name);
console.log(index);
}