前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >TypeScript系列教程十一《装饰器》 -- 方法装饰器

TypeScript系列教程十一《装饰器》 -- 方法装饰器

作者头像
星宇大前端
发布2022-05-06 17:19:50
7780
发布2022-05-06 17:19:50
举报
文章被收录于专栏:大宇笔记

系列教程

方法装饰器在后端编程中见到是比较多的,路由、注入等场景都有大规模的应用。下面是开始学习TS的方法装饰器。

方法装饰器的定义

一个函数,返回 TypedPropertyDescriptor | void 参数如下:

  • target: Object
  • propertyKey:string | symbol
  • descriptor: TypedPropertyDescriptor
代码语言:javascript
复制
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;

不知道什么意思,先写一个简单的例子打印下,看看每一个参数是什么意思,

示例代码:

代码语言:javascript
复制
const get:MethodDecorator = (target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor) => {
  console.log("target:",target);
  console.log("propertyKey:",propertyKey);
  console.log("descriptor:",descriptor);
}

class HttpRequest {
  
  @get
  getAllData(params:{data:[]}){

  }
}

打印结果:

参数意义:

  • target : 对于静态方法是构造函数,普通方法是原型对象
  • propertyKey: 方法名称
  • descriptor : 方法描述 ,
  • descriptor.value : 对于静态方法是构造函数,普通方法是原型对象
  • descriptor.writable : 方法是否可以被重写
  • descriptor.enumerable: 是否可以被枚举
  • descriptor.configurable:是否可以改变、删除

方法装饰器示例

示例思路:

  1. 实现一个get装饰器
  2. get装饰器修饰函数可以拿到request 对象
  3. request 对象是经过装饰器处理塞进函数的

代码示例:

代码语言:javascript
复制
const get:MethodDecorator = (target: Object, propertyKey: string | symbol, descriptor: PropertyDescriptor) => {
    const method = descriptor.value
    descriptor.value = () => {
      method({header:'这是请求头header',body:'请求内容'})
    }
}


interface Request {
  header:string,
  body:string
}

class HttpRequest {
  
  @get
  getAllData(request?:Request){
       console.log(request);
  }
}

let http = new HttpRequest()
http.getAllData()

方法装饰器工厂

方法装饰器工厂类似于类装饰器工厂,工厂加工产生的是方法装饰器。这个工厂需要参数提供条件。

示例思路,之前的例子,我们需要跟上请求路径。

示例代码:

代码语言:javascript
复制
const get: (path: string) => MethodDecorator = (path) => {
  return (
    target: Object,
    propertyKey: string | symbol,
    descriptor: PropertyDescriptor
  ) => {
    const method = descriptor.value;
    (function () {
      method({ header: "这是请求头header", path: path, body: "请求内容" });
    })();
  };
};

interface Request {
  header: string;
  path: string;
  body: string;
}

class HttpRequest {
  @get("/getAll")
  getAllData(request?: Request) {
    console.log(request);
  }


  @get("/getList")
  getList(request?: Request) {
    console.log(request);
  }
}

控制台打印输出:

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-04-02,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 系列教程
    • 方法装饰器的定义
      • 方法装饰器示例
        • 方法装饰器工厂
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档