我有一个抽象类,它在其原型上实现了一些方法,我想直接创建这个类的实例,而不需要对它进行子类化。
我可以通过创建Proxy
并捕获construct
来实例化该类,但它似乎可以正常工作。正确设置了新实例的属性,但我很难调用它的方法。
function AbstractNumbers(...args) {
if (new.target === AbstractNumbers) {
throw new Error('Cannot instantiate abstract class');
}
this.numbers = args;
}
AbstractNumbers.prototype.showNumbers = function() { console.log(this.numbers); }
const AbstractNumbersProxy = new Proxy(AbstractNumbers, {
construct(target, args) {
// change 3rd argument to bypass new.target test
return Reflect.construct(target, args, function() {});
}
});
const n = new AbstractNumbersProxy(1, 2, 3);
// set prototype back to AbstractNumbers
Object.setPrototypeOf(n, AbstractNumbers);
// n.__proto__ shows the correct prototype
console.log(n.__proto__);
// property n.numbers is set correctly
console.log(n.numbers);
// calling its prototype method fail
n.showNumbers();
如何正确实例化该抽象类,以便我能够调用其方法?
答案 0 :(得分:1)
在
// set prototype back to AbstractNumbers
Object.setPrototypeOf(n, AbstractNumbers);
您已将原型设置回构造函数而不是其prototype
属性。试试
Object.setPrototypeOf(n, AbstractNumbers.prototype);
代替:
function AbstractNumbers(...args) {
if (new.target === AbstractNumbers) {
throw new Error('Cannot instantiate abstract class');
}
this.numbers = args;
}
AbstractNumbers.prototype.showNumbers = function() { console.log(this.numbers); }
const AbstractNumbersProxy = new Proxy(AbstractNumbers, {
construct(target, args) {
// change 3rd argument to bypass new.target test
return Reflect.construct(target, args, function() {});
}
});
const n = new AbstractNumbersProxy(1, 2, 3);
// set prototype back to AbstractNumbers
Object.setPrototypeOf(n, AbstractNumbers.prototype);
// n.__proto__ shows the correct prototype
console.log(n.__proto__);
// property n.numbers is set correctly
console.log(n.numbers);
// calling its prototype method fail
n.showNumbers();
请不要让我调查你在做什么。