Javascript 如何检查子类是否重写了父方法/函数?

Javascript 如何检查子类是否重写了父方法/函数?,javascript,inheritance,ecmascript-6,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 MyInte

我在模拟一个接口类:

const error = "Child must implement method";

class MyInterface
{
  normalFunction()
  {
    throw error;
  }

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

class MyImplementation extends MyInterface
{
}
如果在没有重写实现的情况下调用任何接口方法,将抛出错误。但是,这些错误只会在执行时出现


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

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

类MyInterface{
构造函数(){
const proto=Object.getPrototypeOf(this);
const superProto=MyInterface.prototype;
const missing=Object.getOwnPropertyNames(超级协议).find(名称=>
超级协议的类型[名称]=“函数”&&!proto.hasOwnProperty(名称)
);
if(missing)抛出新的TypeError(`${this.constructor.name}需要实现${missing}`);
}
normalFunction(){}
异步函数(){}
}
类MyImplementation扩展了MyInterface{}
//触发错误:

新的MyImplementation()您不能使用反射来列出一个类的所有函数吗


例如,这里给我们一个函数,它列出了一个对象的所有函数。一旦你得到了所有这些,你就可以看到你是否有一个被重写的函数。

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