zoukankan      html  css  js  c++  java
  • 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);

     待完善

  • 相关阅读:
    ES6 => 箭头函数
    从零开始, 探索transition(vue-2.0)
    从零开始,零基础,一点一点探索vue-router(vue2.0)
    解决Vue请求 ‘No 'Access-Control-Allow-Origin' header is present on the requested resource’错误
    超详细,用canvas在微信小程序上画时钟教程
    钱兔
    天天飞燕
    小鱼
    键盘处理
    兼容iOS 10 资料整理笔记
  • 原文地址:https://www.cnblogs.com/codexlx/p/12775249.html
Copyright © 2011-2022 走看看