可动态获取实例化对象的Typescript装饰器

引用自 摸鱼wiki

1. 何为装饰器

装饰器是一种特殊类型的声明,它能够被附加到类声明,方法, 访问符,属性或参数上。 装饰器使用 @expression这种形式,expression求值后必须为一个函数,它会在运行时被调用,被装饰的声明信息做为参数传入。

2. 调用时机

// @experimentalDecorators
function decorator() {
  console.log("decorator(): factory evaluated");
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    console.log("decorator(): called");
  };
}

class ExampleClass {
  @decorator()
  method() {
    console.log('method call');
  }

  constructor() {
    console.log('instance call');
  }
}

const ins = new ExampleClass();

ins.method();

在运行的时候发现,装饰器在类实例化前已经完成数据绑定操作,这时候在装饰器内部是没有办法拿到绑定对象的实例的,target对应的是ExampleClass的定义,而不是实例化后的对象。这时候在装饰器内部调用实例上的方法会报错。

[LOG]: "decorator(): factory evaluated" 
[LOG]: "decorator(): called" 
[LOG]: "instance call" 
[LOG]: "method call" 

3. 应对方案

Typescript/Javascript为实例化对象提供了一种访问器属性:getter/setter。只有在类实例化后,调用具体方法名才会执行。那对于装饰器来说,如果返回一个带有getter/setter的方法,那是否也可以把执行时机延后,等到拿到类实例化对象后再执行?

举个例子,假如当前类中有一个 preTask 函数需要在method函数前面执行,需要怎么做?我们稍微改造一下装饰器的实现,这时候装饰器返回的是一个带有getter的对象,getter在调用的时候,由于使用的是function声明,这时候this指向ExampleClass实例化后的对象,继而实现调用实例上的方法。

// @experimentalDecorators
function decorator() {
  console.log("decorator(): factory evaluated");
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const fn = descriptor.value;
    return {
      configurable: true,
      get() {
        console.log("decorator(): called");
        const boundFn = ((...args: any) => {
          (this as any).preTask();
          fn.bind(this)(...args);
        }).bind(this);
        return boundFn;
      }
    }
  };
}

class ExampleClass {
  @decorator()
  method() {
    console.log('method call');
  }

  preTask() {
    console.log('preTask call');
  }

  constructor() {
    console.log('instance call');
  }
}

const ins = new ExampleClass();

ins.method();

执行结果如下:

[LOG]: "decorator(): factory evaluated" 
[LOG]: "instance call" 
[LOG]: "decorator(): called" 
[LOG]: "preTask call" 
[LOG]: "method call" 

可以发现装饰器的运行时机被延后到类实例化后,从而能够调用类实例化对象上的方法。

4. 参考

[1] https://github.com/andreypopp/autobind-decorator/blob/master/src/index.js

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZTao-z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值