【发布时间】: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