Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

antd源码中throttleByAnimationFrameDecorator的疑惑

先贴源码(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没派上用场啊?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...