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

sup*_*tle 4 javascript oop inheritance instanceof typescript

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

为什么会这样?

编辑

所以我发现这只发生在我用 Error 类扩展 Child 类时。让我留下下面的代码示例。

class Child extends Error {
  constructor(message) {
    super(message);
  }
}
const ch = new Child();
console.log(ch instanceof Child);
Run Code Online (Sandbox Code Playgroud)

第二次编辑

class PullCreditError extends Error {
  public name: string;
  public message: string;
  public attemptsRemaining: number;
  constructor(message: string, attemptsRemaining: number) {
    super();
    Error.captureStackTrace(this, PullCreditError);
    this.name = 'PullCreditError';
    this.message = message;
    this.attemptsRemaining = attemptsRemaining;
  }
}
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 7

这是一个记录在案的错误:

https://github.com/Microsoft/TypeScript/issues/15875

扩展 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;
  }
}
Run Code Online (Sandbox Code Playgroud)