typescript 装饰器用法

函数装饰器

function testDecorator(isTrue: boolean){
    console.log("111111111")
    if(isTrue){
        return function(class_name: any){
            console.log("2222222")
            console.log(class_name) // 输出的是类名
            class_name.prototype.getName= () => {  // 给类添加方法(在原型上添加相当于在类上添加)
                console.log('dell');
            };
        }
    }else{
        return function(class_name: any){}
    }
}

function decorator(class_name: any){
    console.log("333333333")
    console.log(class_name) // 输出的是类名
    class_name.prototype.getName= () => {  // 给类添加方法(在原型上添加相当于在类上添加)
        console.log("44444444")
        console.log('dell~');
    }
};

@testDecorator(true)
@decorator  // 
class AAA {
   constructor(){console.log('aaa')} 
}

const aaa = new AAA();
(aaa as any).getName()


// 输出结果
/*
111111111  说明先装饰最上边的,即装饰顺序是从上到下(定义装饰)
333333333
[class AAA]
2222222     属性装饰则是上边的装饰器装饰的晚,把下边先装饰的同名函数给替换了
[class AAA]  即内容的装饰是从下往上(内容装饰)
aaa   先构造
dell  再调用
*/ 

上边的变形


function testDecorator() {
    return function<T extends new (...args: any[]) => any>(constructor: T) {
      return class extends constructor {
        name = 'lee'; // 装饰后就更改了之前的name值
        getName() {
          return this.name;
        }
      };
    };
  }
  
//  变相的装饰器这样的装饰器可以有提示
const Test = testDecorator()(
class {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
}
);

const test = new Test('dell');
console.log(test.getName());  // lee
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值