javascript - 如何在javascript中调用抽象类的方法
问题描述
我有一个抽象类,它在其原型上实现了一些方法,我想直接创建这个类的一个实例而不对其进行子类化。
我可以通过创建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();
如何正确实例化该抽象类以便能够调用它的方法?
解决方案
在
// 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();
请不要让我调查你在做什么。
推荐阅读
- sql - BigQuery - 使用字符串和数组加入两个表
- faunadb - 如何将 q.Now() 结果转换为动物群中的字符串
- mongodb - 如何获取名称中带有空格字符的集合的信息?
- php - cURL 无法使用 PHP 连接,但可以通过 IDE 连接
- javascript - 使用打字稿定义 InfiniteScroll 反应组件的类型
- r - 在 R 中选择独特的工作场所 - id 组合
- java - jSS7中的SendParameters奇怪的行为
- r - R 中的优化 - 给每个场合一个组长,每个人都应该至少被选择一次
- python - 根据列名中是否存在后缀对列进行排序
- python - 带有大型视频文件的 jupyter 中的 mattplotlib 动画