在 JavaScript 中继承 Class(函数)的代理时发生了什么
What's happening when inheriting a Proxy of Class (Function) in JavaScript
我想继承一个带有代理构造函数的函数,如下面的 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'; }
}
但是,它并没有起作用; Subclass 方法似乎未绑定在 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
class SubB 中发生了什么,我该如何修复它(或者是否可能)?
您忽略了 ,这就是为什么您的代理构造函数创建的实例总是仅继承自 Base
(代理处理程序中的 target
),而不继承自SubB
.
你应该使用 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'; }
}
我想继承一个带有代理构造函数的函数,如下面的 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'; }
}
但是,它并没有起作用; Subclass 方法似乎未绑定在 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
class SubB 中发生了什么,我该如何修复它(或者是否可能)?
您忽略了 Base
(代理处理程序中的 target
),而不继承自SubB
.
你应该使用 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'; }
}