【问题标题】:Why instanceof returns false for a child object in Javascript为什么instanceof在Javascript中为子对象返回false
【发布时间】:2018-12-16 04:40:35
【问题描述】:

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

【问题讨论】:

  • @CertainPerformance 我添加了我的代码示例。我实际上有 Child 类继承自 javascript Error 类。
  • 这看起来不像 javascript。你确定你没有使用java吗?
  • @PhilippSander 你以前从未见过 JavaScript 类吗?
  • 我从未见过“构造函数”。这只是一个问题。我可能错了。
  • @PhilippSander 欢迎来到 ES2015:P

标签: javascript typescript oop inheritance instanceof


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多