TypeScript-方法装饰器
  TEZNKK3IfmPf 2023年11月14日 31 0
  • 方法装饰器写在,在一个方法的声明之前(紧靠着方法声明)
  • 方法装饰器可以用来监视,修改或者替换方法定义

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

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

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

@test
static say(): void {
console.log('say hello world');
}
}

TypeScript-方法装饰器

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

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

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

TypeScript-方法装饰器

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

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

TypeScript-方法装饰器

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2023年11月14日   34   0   0 typescript
  TEZNKK3IfmPf   2023年11月14日   24   0   0 typescript
  TEZNKK3IfmPf   2023年11月14日   30   0   0 typescript
  TEZNKK3IfmPf   2024年04月19日   33   0   0 typescript数组编译器
  TEZNKK3IfmPf   2023年11月14日   25   0   0 typescript装饰器
  TEZNKK3IfmPf   2023年11月14日   32   0   0 typescript
TEZNKK3IfmPf