TypeScript--方法装饰器,装饰器的执行顺序

1. TypeScript–方法装饰器,装饰器的执行顺序


1.1 方法装饰器

    它会被应用到方法的 属性描述符上,可以用来监视,修改或者替换方法定义。

    方法装饰会在运行时传入下列3个参数:
        1、对于静态成员来说是类的构造函数,对于实例成员是类的原型对象。
        2、成员的名字。
        3、成员的属性描述符。

1.2.1 方法装饰器示例02:添加方法

//方法装饰器一

function get(params: any) {
  return function (target: any, methodName: any, desc: any) {
    console.log(target);
    console.log(methodName);
    console.log(desc);
    target.apiUrl = "xxxx";
    target.run = function () {
      console.log("run");
    };
  };
}

class HttpClient {
  public url: any | undefined;
  constructor() {}
  @get("http://www.itying,com")
  getData() {
    console.log(this.url);
  }
}

var http: any = new HttpClient();
console.log(http.apiUrl);
http.run();

1.3.2 方法装饰器示例02:修改方法

desc.value代表当前方法

function get(params: any) {
  return function (target: any, methodName: any, desc: any) {
    console.log(desc.value);

    //修改装饰器的方法  把装饰器方法里面传入的所有参数改为string类型
    //1、保存当前的方法
    var oMethod = desc.value;
    desc.value = function (...args: any[]) {
      args = args.map((value) => {
        return String(value);
      });
      oMethod.apply(this, args);
    };
  };
}

class HttpClient {
  public url: any | undefined;
  constructor() {}
  @get("http://www.itying,com")
  getData(...args: any[]) {
    console.log(args);
    console.log("我是getData里面的方法");
  }
}

var http = new HttpClient();
http.getData(123, "xxx");

1.4 装饰器的执行顺序

  • 属性 > 方法 > 方法参数 > 类
  • 如果有多个同样的装饰器,它会先执行后面的


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CodeJiao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值