tkondo
tkondo

Reputation: 13

What's happening when inheriting a Proxy of Class (Function) in JavaScript

I want to inherit a function with proxied constructor, like SubB below;

const Base = function () {};
Base.prototype.baseMethod = function () { return 'base method'; }

class SubA extends (new Proxy(Base, {})) {
    subMethod () { return 'sub method'; }
}

const handler = { construct: (target, args) => new target(...args) };
class SubB extends (new Proxy(Base, handler)) {
    subMethod () { return 'sub method'; }
}

However, it does not work collectly; Subclass methods seems not to be bound in SubB.

(new SubA()).baseMethod(); //=> "base method"
(new SubB()).baseMethod(); //=> "base method"

(new SubA()).subMethod(); //=> "sub method"
(new SubB()).subMethod();
  //=> Uncaught TypeError: (intermediate value).subMethod is not a function

What's happening in class SubB and how can I fix it (or is it possible)?

Upvotes: 1

Views: 913

Answers (1)

Bergi
Bergi

Reputation: 664484

You are ignoring new.target, which is why the instance that your proxied constructor creates always inherits from the Base (the target in the proxy handler) only, and not from the SubB.

You should use Reflect.construct as the default action of the construct trap:

const handler = {
  construct(target, args, newTarget) {
    return Reflect.construct(target, args, newTarget);
  }
};
class SubB extends (new Proxy(Base, handler)) {
  subMethod () { return 'sub method'; }
}

Upvotes: 1

Related Questions