如何检查Child类是否重写了Parent方法/函数?

时间:2019-05-03 14:16:37

标签: javascript inheritance ecmascript-6

我在嘲笑接口类:

const error = "Child must implement method";

class MyInterface
{
  normalFunction()
  {
    throw error;
  }

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

class MyImplementation extends MyInterface
{
}

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

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

2 个答案:

答案 0 :(得分:2)

您可以在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)

答案 1 :(得分:0)

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

例如,这里https://stackoverflow.com/a/31055217/10691359给我们提供了一个列出对象所有功能的功能。一旦获得所有这些,就可以查看是否具有覆盖的功能。

相关问题