antd源码中throttleByAnimationFrameDecorator的疑惑

发布于 2022-09-12 03:05:19 字数 1388 浏览 22 评论 0

先贴源码(components/_util/throttleByAnimationFrame)

export function throttleByAnimationFrameDecorator() {
  return function(target: any, key: string, descriptor: any) {
    let fn = descriptor.value;
    let definingProperty = false;
    return {
      configurable: true,
      get() {
        if (definingProperty || this === target.prototype || this.hasOwnProperty(key)) {
          return fn;
        }

        let boundFn = throttleByAnimationFrame(fn.bind(this));
        definingProperty = true;
        Object.defineProperty(this, key, {
          value: boundFn,
          configurable: true,
          writable: true,
        });
        definingProperty = false;
        return boundFn;
      },
    };
  };
}

使用实例(component/affix/index)

export default class Affix extends React.Component<AffixProps, AffixState> {
  ...

  @throttleByAnimationFrameDecorator()
  updatePosition(e: any) {
     ...
  }
  
  ...
}

疑惑有两点
1:这个方法有必要返回一个装饰器函数吗,为什么不直接当做装饰器设计,就不用每次需要显示调用。
2:let definingProperty = false;这一个变量好像没用?

先说一下自己的理解:
1:是为了向后扩展兼容,方便为了传参,或统一装饰器的使用,于是都设计成这种装饰器创建函数,还是处于其他考虑。
2:第一次实例化时,闭包创建了一个definingProperty,返回的getter将原型方法的描述修改了,对组件实例Object.defineProperty添加了一个同名方法。重复使用组件,再次实例会直接走getter,这时新的组件实例又会被添加一个同名方法。感觉definingProperty没派上用场啊?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文