【问题标题】:How to check if Child class has overridden Parent method/function?如何检查子类是否已覆盖父方法/函数?
【发布时间】:2019-05-03 14:16:37
【问题描述】:

我在模拟一个接口类:

const error = "Child must implement method";

class MyInterface
{
  normalFunction()
  {
    throw error;
  }

  async asyncFunction()
  {
    return new Promise(() => Promise.reject(error));
  }
}

class MyImplementation extends MyInterface
{
}

如果在没有覆盖实现的情况下调用任何接口方法,则会引发错误。但是,这些错误只会在执行时出现。

有没有办法检查函数在构造时是否被覆盖?

【问题讨论】:

  • "at construction": 你的意思是MyImplementation的实例的构造?
  • @trincot 是的,很可能在 MyInterface 构造函数中
  • 您必须实现类似工厂模式的东西来执行该检查。我不认为 JS 有原生的东西可以做到这一点。
  • 顺便说一句:你可以在throwasync函数中的错误:这将导致返回的承诺被拒绝。
  • @trincot 是的。我这样做是为了加强函数的“异步性”。我有点忙,但很快就会看看你的解决方案

标签: javascript inheritance ecmascript-6


【解决方案1】:

您可以在MyInterface 的构造函数中添加一些检查,如下所示:

class MyInterface {
    constructor() {
        const proto = Object.getPrototypeOf(this);
        const superProto = MyInterface.prototype;
        const missing = Object.getOwnPropertyNames(superProto).find(name =>
            typeof superProto[name] === "function" && !proto.hasOwnProperty(name)
        );
        if (missing) throw new TypeError(`${this.constructor.name} needs to implement ${missing}`);
    }

    normalFunction() {}

    async asyncFunction() {}
}

class MyImplementation extends MyInterface {}

// Trigger the error:
new MyImplementation();

请注意,仍有一些方法可以在不运行构造函数的情况下创建MyImplementation 的实例:

Object.create(MyImplementation.prototype)

【讨论】:

    【解决方案2】:

    你不能使用反射来列出一个类的所有功能吗?

    例如这里https://stackoverflow.com/a/31055217/10691359 给我们一个函数,它列出了一个对象的所有函数。一旦你得到所有这些,你就可以看到你是否有一个被覆盖的函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-13
      • 1970-01-01
      • 2021-12-15
      • 2020-06-27
      • 1970-01-01
      • 2018-03-06
      相关资源
      最近更新 更多