【问题标题】:Proxy ES6 class and maintain prototype chain代理 ES6 类并维护原型链
【发布时间】:2019-02-22 20:57:51
【问题描述】:

我正在使用以下包装器代理方法:

  public static wrap(target) {
    function construct(constructor, args) {
      const c: any = function(this) {
        return constructor.apply(this, args);
      };

      c.prototype = constructor.prototype;
      return new c();
    }

    const f = (...args) => {
      const instance = construct(target, args);

      const descriptors = getMethodDescriptors(target, instance);

      return new Proxy<T>(
        instance,
        new SomeProxyHandler(descriptors)
      );
    };

    f.prototype = target.prototype;
    return f;
  }

这在包装编译为 ES5 的类时效果很好,但现在我尝试针对 ES6 我在constructor.apply(this, args) 收到错误说:

TypeError: Class constructor OneOfMyClasses cannot be invoked without 'new'

如何修复此代码,以便wrap 可以代理任何 JavaScript 目标的类并维护正确的原型链?

【问题讨论】:

标签: javascript ecmascript-6 proxy


【解决方案1】:

最简单的方法是传播语法

const instance = new target(...args);

但你也可以使用Reflect.construct:

const instance = Reflect.construct(target, args);

如果您的包装类应该是可扩展的,这甚至是必要的,那么您将不得不使用new.target

const instance = Reflect.construct(target, args, new.target);

顺便说一句,你的f 包装器应该是proper function not an arrow function,因为它们不能用new 调用(并且没有new.target)。或者更简单(使用静态方法和继承更好地工作),只需将整个 target 类本身包装在 Proxy 中并使用它的 construct trap

【讨论】:

    猜你喜欢
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-19
    • 2015-10-20
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多