Tuesday 26 February 2019

Proxy ES6 class and maintain prototype chain

I'm proxying methods using the following wrapper:

  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;
  }

This has worked well when wrapping classes which are compiled down to ES5 but now I'm trying to target ES6 I'm getting errors at constructor.apply(this, args) saying that:

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

How can I fix this code so wrap can proxy classes whatever the JavaScript target and maintain the correct prototype chain?



from Proxy ES6 class and maintain prototype chain

No comments:

Post a Comment