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 @   BNTang  阅读(160)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
点击右上角即可分享
微信分享提示