es7装饰器

最近终于上手了node服务,这样一来前端的技术栈又拓宽了许多。这次的项目是公司内部项目用的是nestjs,头一次接触到nestjs最深刻的印象就是打来给你用到了es7的装饰器。在项目开始的时候就预料到要写博客了,知识点很多那就先从装饰器开始吧。

装饰器在其他的语言上已经被广泛的使用了如java,py等。js es7的装饰器可以分为四种分别是类装饰器、方法装饰器、变量装饰器、参数装饰器。装饰器本身也相当于是封装了一个逻辑方法,在使用的时候通过@标识符直接调用。

目前浏览器和node对装饰器的支持还不是很好需要安装相应的babel。
我自己的测试项目的话是用vite,因此还涉及到了ts,我的配置是如下:

tsconfig.json

{
  "compilerOptions": {
    "experimentalDecorators": true
  }
}

vite.config.ts 

import typescript from "@rollup/plugin-typescript";
export default defineConfig({
  plugins: [
    typescript({
      include: ["src/page/nestjs/**/*"],
      exclude: ["node_modules/**/*"],
    }),
    react({
      babel: {
        plugins: [
          ["@babel/plugin-proposal-decorators", { legacy: true }],
          ["@babel/plugin-proposal-class-properties", { loose: true }],
        ],
      },
    }),
  ],
});

example 

const decoratorTest = () => {
  function classDecorator(classObj: any) {
    console.log("classDecorator", classObj);
  }

  function functionDecorator(target: User, name: string, descriptor: any) {
    console.log("functionDecorator", target, name, descriptor);
  }

  function filedDecorator(filed: string) {
    return function (target: User, name: string, descriptor: any) {
      console.log("filedDecorator", target, name, descriptor, filed);
    };
  }

  function valueDecorator(target: User, propertyKey: string) {
    console.log("valueDecorator", target, propertyKey);
  }

  function paramsDecorator(
    target: any,
    methodName: string,
    paramsIndex: number
  ) {
    console.log("paramsDecorator", target, methodName, paramsIndex);
  }
  @classDecorator
  class User {
    @valueDecorator
    public name: string = "234234";
    constructor() {}
    @filedDecorator("234234234")
    @functionDecorator
    getName() {
      return "111";
    }
    testParams(@paramsDecorator params: string) {
      console.log(params);
    }
  }
  let user = new User();
  console.log(user.getName());
  user.testParams("234234");
};

前端的话装饰器的使用暂时还不是很多,目前的前端有使用到的场景也就是mobx。
对于装饰器的话个人更把装饰器看成是一种另类的封装。不过这里也得到了一定的启发就是函数柯里化的应用。例如上面例子中的functionDecorator装饰器,普通装饰器是不能直接传递参数的,通过包裹一层函数的方式然后返回一个函数的方式就可以实现装饰器的传参。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值