1

我想继承一个带有代理构造函数的函数,比如下面的 SubB;

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

但是,它不能集体工作;子类方法似乎未绑定在 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

SubB 类发生了什么,我该如何解决(或者可能)?

4

1 回答 1

1

您正在忽略new.target,这就是为什么您的代理构造函数创建的实例始终仅从Basetarget代理处理程序中的)继承,而不是从SubB.

您应该使用Reflect.construct作为construct陷阱的默认操作:

const handler = {
  construct(target, args, newTarget) {
    return Reflect.construct(target, args, newTarget);
  }
};
class SubB extends (new Proxy(Base, handler)) {
  subMethod () { return 'sub method'; }
}
于 2017-11-13T15:55:51.897 回答