TypeScript-方法装饰器

2023-09-29 22:31:05 浏览数 (1)

方法装饰器

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

方法装饰器表达式会在运行时当中函数会被调用,会自动传入下列 3 个参数给方法装饰器:

  • 对于静态方法而言就是当前的类, 对于实例方法而言就是当前的实例

实例方法:

代码语言:typescript复制
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 yangbuyiya');
    }

    sayAge(): void {
        console.log('my age is 34');
    }

    static say(): void {
        console.log('say hello world');
    }
}
image-20211206094018887image-20211206094018887

静态方法:

代码语言:typescript复制
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 yangbuyiya');
    }

    sayAge(): void {
        console.log('my age is 34');
    }

    @test
    static say(): void {
        console.log('say hello world');
    }
}
image-20211206094110613image-20211206094110613
  • 被绑定方法的名字
  • 被绑定方法的属性描述符

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

代码语言:typescript复制
function test(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    descriptor.enumerable = false;
}

class Person {
    sayName(): void {
        console.log('my name is yangbuyiya');
    }

    @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-20211206094305185image-20211206094305185

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

代码语言:typescript复制
function test(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    descriptor.value = (): void => {
        console.log('my name is yangbuyiya');
    };
}

class Person {
    @test
    sayName(): void {
        console.log('my name is Person');
    }
}

let p = new Person();
p.sayName();
image-20211206104853870image-20211206104853870

最后

本期结束咱们下次再见

0 人点赞