如何在javascript中调用抽象类的方法

如何在javascript中调用抽象类的方法,javascript,reflection,ecmascript-6,Javascript,Reflection,Ecmascript 6,我有一个抽象类,它在原型上实现了一些方法,我想直接创建这个类的一个实例,而不需要对它进行子类化 我可以通过创建一个代理并捕获构造来实例化该类,它似乎可以工作。新实例的属性设置正确,但我很难调用它的方法 函数抽象数(…args){ if(new.target==AbstractNumber){ 抛出新错误('无法实例化抽象类'); } this.numbers=args; } AbstractNumbers.prototype.showNumbers=function(){console.log

我有一个抽象类,它在原型上实现了一些方法,我想直接创建这个类的一个实例,而不需要对它进行子类化

我可以通过创建一个
代理
并捕获
构造
来实例化该类,它似乎可以工作。新实例的属性设置正确,但我很难调用它的方法

函数抽象数(…args){
if(new.target==AbstractNumber){
抛出新错误('无法实例化抽象类');
}
this.numbers=args;
}
AbstractNumbers.prototype.showNumbers=function(){console.log(this.numbers);}
const AbstractNumbersProxy=新代理(AbstractNumbers{
构造(目标,args){
//将第三个参数更改为绕过new.target测试
返回Reflect.construct(目标、参数、函数(){});
}
});
const n=新的AbstractNumbersProxy(1,2,3);
//将原型设置回抽象数字
setPrototypeOf(n,AbstractNumber);
//n.uuu proto_uuu显示了正确的原型
console.log(n.\uuuu proto\uuuu);
//属性n.编号设置正确
控制台日志(n.编号);
//调用其原型方法失败
n、 showNumber()

您已将原型设置回构造函数,而不是其
prototype
属性。试一试

Object.setPrototypeOf(n, AbstractNumbers.prototype);
相反:

函数抽象数(…args){
if(new.target==AbstractNumber){
抛出新错误('无法实例化抽象类');
}
this.numbers=args;
}
AbstractNumbers.prototype.showNumbers=function(){console.log(this.numbers);}
const AbstractNumbersProxy=新代理(AbstractNumbers{
构造(目标,args){
//将第三个参数更改为绕过new.target测试
返回Reflect.construct(目标、参数、函数(){});
}
});
const n=新的AbstractNumbersProxy(1,2,3);
//将原型设置回抽象数字
setPrototypeOf(n,AbstractNumber.prototype);
//n.uuu proto_uuu显示了正确的原型
console.log(n.\uuuu proto\uuuu);
//属性n.编号设置正确
控制台日志(n.编号);
//调用其原型方法失败

n、 showNumber()@zerkms你是什么意思<代码>构造
是构造函数的陷阱。
Object.setPrototypeOf(n, AbstractNumbers.prototype);