首页 > 解决方案 > 如何在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();

如何正确实例化该抽象类以便能够调用它的方法?

标签: javascriptreflectionecmascript-6

解决方案


// 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();

请不要让我调查你在做什么。


推荐阅读