装饰器

装饰器就是一个方法,可以注入到,类、方法、属性参数上来扩展他们的功能

类装饰器(无法传参)

(function () {
  function fun1(target: any): void {
    target.prototype.name = "张三";
    target.class = "humen";
  }

  @fun1
  class Person {}
  const p = new Person();
  //@ts-ignore
  console.log(p.name);
  //@ts-ignore
  console.log(Person.class);
})();

// 和下面代码等价

(function () {
  function fun1(target: any): void {
    target.prototype.name = "张三";
    target.class = "humen";
  }
  class Person {}
  fun1(Person);
  const p = new Person();
  //@ts-ignore
  console.log(p.name);
  //@ts-ignore
  console.log(Person.class);
})();

装饰器工厂,解决类装饰器不能传参的问题

(function () {
  function fun1(option: Record<string, any>) {
    return function (target: any) {
      target.prototype.name = option.name;
      target.class = option.class;
    };
  }

  @fun1({
    name: "张三",
    class: "humen",
  })
  class Person {}
  const p = new Person();
  //@ts-ignore
  console.log(p.name);
  //@ts-ignore
  console.log(Person.class);
})();

// 和下面代码等价

(function () {
  /**
   * @fun1() 执行,返回的就是其内部得函数,其后面结果和类装饰器就是一样的
   */
})();

装饰器组合(装饰器从下到上执行)

(function () {
  function fun1(target: any) {
    target.fun1 = "ok";
  }

  function fun2(option: any) {
    return function (target: any) {
      target.fun2 = option.ok;
    };
  }

  @fun1
  @fun2({ ok: "ok" })
  class Person {}

  // fun2装饰后,再把结果交给fun1装饰

  //@ts-ignore
  console.log(Person.fun1)
  //@ts-ignore
  console.log(Person.fun2)
})();

属性装饰器

(function () {
  function fun(target: any, functionName: string) {
    
    // target类本身(Person)
    // functionName被装饰的方法名字(sayName)
    
    console.log(target, functionName);
  }

  class Person {
    @fun
    sayName() {
      console.log("my name is llc");
    }
  }

  const p = new Person()
  p.sayName()
})();

posted on 2022-10-05 14:59  In-6026  阅读(14)  评论(0编辑  收藏  举报

导航