- 方法装饰器写在,在一个方法的声明之前(紧靠着方法声明)
- 方法装饰器可以用来监视,修改或者替换方法定义
方法装饰器表达式会在运行时当中函数会被调用,会自动传入下列 3 个参数给方法装饰器:
- 对于静态方法而言就是当前的类, 对于实例方法而言就是当前的实例
实例方法:
function test(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
console.log(target);
console.log(propertyKey);
console.log(descriptor);
}
class Person {
@test
sayName(): void {
console.log('my name is BNTang');
}
sayAge(): void {
console.log('my age is 34');
}
static say(): void {
console.log('say hello world');
}
}
静态方法:
function test(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
console.log(target);
console.log(propertyKey);
console.log(descriptor);
}
class Person {
sayName(): void {
console.log('my name is BNTang');
}
sayAge(): void {
console.log('my age is 34');
}
@test
static say(): void {
console.log('say hello world');
}
}
剩下的两个参数就不详细的介绍了,接下来看几个案例即可,第一个就是将装饰了方法修饰器的方法在迭代遍历的时候不进行遍历代码实现如下:
function test(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
descriptor.enumerable = false;
}
class Person {
sayName(): void {
console.log('my name is BNTang');
}
@test
sayAge(): void {
console.log('my age is 34');
}
static say(): void {
console.log('say hello world');
}
}
let p = new Person();
for (let key in p) {
console.log(key);
}
第二个案例就比较高级,就是如上所说的替换旧方法的定义返回一个新的方法定义:
function test(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
descriptor.value = (): void => {
console.log('my name is BNTang');
};
}
class Person {
@test
sayName(): void {
console.log('my name is Person');
}
}
let p = new Person();
p.sayName();
|
请发表评论