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

标签 javascript typescript oop inheritance instanceof

我有扩展父类的子类。 假设我从 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);

第二次编辑

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;
  }
}

最佳答案

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

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

Extending built-ins like Error, Array, and Map may no longer work

As part of substituting the value of this with the value returned by a super(...) call, subclassing Error, Array, and others may no longer work as expected. This is due to the fact that constructor functions for Error, Array, and the like use ECMAScript 6's new.target to adjust the prototype chain; however, there is no way to ensure a value for new.target when invoking a constructor in ECMAScript 5. Other downlevel compilers generally have the same limitation by default.

建议在构造函数中使用setPrototypeOf 手动调整原型(prototype)。 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;
  }
}

关于javascript - 为什么 instanceof 在 Javascript 中为子对象返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51229574/

相关文章:

java - 类和函数结构(Java)

javascript - 如何在 Electron 应用程序中获取持久权限?

javascript - 用于文本输入的 AngularJS 指令 : focus on next input on Enter

typescript - 在angular2中调用typescript getter

Javascript继承范围问题

c++ - 对象池的替代方案?

javascript - BLE主控: scanning while connected

javascript - 当 css 显示无阻止时对象标记重新加载

typescript - 将 useState 输出的 typescript 设置为对象数组的元素之一

点击事件类型的 TypeScript jQuery