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