TypeScript-方法装饰器

方法装饰器

  • 方法装饰器写在,在一个方法的声明之前(紧靠着方法声明)
  • 方法装饰器可以用来监视,修改或者替换方法定义

方法装饰器表达式会在运行时当中函数会被调用,会自动传入下列 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');
    }
}

image-20211206094018887

静态方法:

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');
    }
}

image-20211206094110613

  • 被绑定方法的名字
  • 被绑定方法的属性描述符

剩下的两个参数就不详细的介绍了,接下来看几个案例即可,第一个就是将装饰了方法修饰器的方法在迭代遍历的时候不进行遍历代码实现如下:

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);
}

image-20211206094305185

第二个案例就比较高级,就是如上所说的替换旧方法的定义返回一个新的方法定义:

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();

image-20211206104853870

posted @ 2021-12-05 22:45  BNTang  阅读(154)  评论(0编辑  收藏  举报