为什么instanceof在Javascript中为子对象返回false

为什么instanceof在Javascript中为子对象返回false,javascript,typescript,oop,inheritance,instanceof,Javascript,Typescript,Oop,Inheritance,Instanceof,我有扩展父类的子类。 假设我在child类中创建了一个新实例“child”。 当我检查child的条件child instanceof时,它返回false。 但是,父级的子实例返回true 为什么会这样 编辑 所以我发现只有在用Error类扩展子类时才会发生这种情况。 让我留下下面的代码示例 类子级扩展错误{ 构造函数(消息){ 超级(信息); } } const ch=新的子对象(); console.log(ch instanceof Child)这是一个记录在案的错误: 扩展诸如Err

我有扩展父类的子类。 假设我在child类中创建了一个新实例“child”。 当我检查child的条件
child instanceof
时,它返回false。 但是,父级的子实例返回true

为什么会这样

编辑

所以我发现只有在用Error类扩展子类时才会发生这种情况。 让我留下下面的代码示例

类子级扩展错误{
构造函数(消息){
超级(信息);
}
}
const ch=新的子对象();

console.log(ch instanceof Child)这是一个记录在案的错误:

扩展诸如Error、Array和Map之类的内置功能可能不再有效

作为用super(…)调用返回的值替换this值的一部分,子类化Error、Array和其他可能不再按预期工作。这是因为Error、Array等的构造函数函数使用ECMAScript 6的new.target来调整原型链;但是,在ECMAScript 5中调用构造函数时,无法确保new.target的值。默认情况下,其他底层编译器通常具有相同的限制

建议在构造函数中使用
setPrototypeOf
手动调整原型。您的
PullCreditError
类的修复程序如下所示:

export class PullCreditError extends Error {
  public name: string;
  public message: string;
  public attemptsRemaining: number;
  constructor(message: string, attemptsRemaining: number) {
    super();
    Object.setPrototypeOf(this, PullCreditError.prototype); // <-------
    Error.captureStackTrace(this, PullCreditError);
    this.name = 'PullCreditError';
    this.message = message;
    this.attemptsRemaining = attemptsRemaining;
  }
}
导出类PullCreditError扩展错误{
公共名称:字符串;
公共消息:字符串;
公共尝试维护:编号;
构造函数(消息:string,尝试维护:number){
超级();

Object.setPrototypeOf(this,PullCreditError.prototype);/@CertainPerformance我添加了我的代码示例。我实际上从javascript错误类继承了子类。这看起来不像javascript。你确定你没有使用java吗?@PhilippSander你以前从未见过javascript类吗?我从未见过“构造函数”。这只是个问题。我可能错了。@PhilippSander欢迎来到ES2015:P