TS之装饰器② 方法装饰器&方法参数装饰器


3.方法装饰器:

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

  方法装饰会在运行时传入下列三个参数:

  (1)对于静态成员来说是类的构造函数,对于实例成员是类的原型对象

  (2)成员的名字

  (3)成员的属性描述

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

    // 扩展属性
    target.apiUrl = 'xxx';
    // 扩展方法
    target.run = function () {
      console.log('run');
    }

    // 修改装饰器的方法,把装饰器方法里面传入的参数都改为string类型
    // (1)保存当前的方法
    let oMethod = desc.value;
    // (2)改写方法
    desc.value = function (...arr: any[]) {
      arr = arr.map(e => {
        return String(e);
      })

      // 调用未改写的方法
      oMethod.apply(this, arr);
      console.log(arr);

    }
  }
}

class HttpClient {
  public url: any | undefined;
  constructor() {

  }

  @get('http://www.baidu.com')
  getData(...arr: any[]) {
    console.log('我是getData里面的方法');
  }
}

let http: any = new HttpClient();
console.log(http.apiUrl);
http.getData('张三', 25);

2.方法参数装饰器

  参数装饰器表达式会在运行时当作函数被调用,可以使用参数装饰器为类的原型增加一些元素数据,传入下列三个参数:

  • 对于静态成员来说是类的构造函数,对于实例成员是类的原型对象
  • 参数的名字
  • 参数在函数参数列表中的索引
function logParams(params: any) {
  return function (target: any, methodName: any, paramsIndex: any) {
    console.log(1, params);
    console.log(2, target);
    console.log(3, methodName);
    console.log(4, paramsIndex);

    // 增加属性
    target.apiUrl = params;

  }
}

class HttpClient {
  public url: any | undefined;
  constructor() {

  }

  getData(@logParams('uuid') uuid: any) {
    console.log('我是getData里面的方法,uuid=', uuid);
  }
}

let http = new HttpClient();

http.getData(123456);

console.log(5, http.apiUrl);

 

 待完善


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM