【发布时间】:2020-11-10 19:57:41
【问题描述】:
我只是不明白,为什么在对象继承中“instanceof”无法将“子”对象评估为父原型的实例。例如:
function Parent(property) {
this.property = property;
}
function Child(property) {
Parent.call(property);
}
const child = new Child("");
console.log(child instanceof Child); // of course, true
console.log(child instanceof Parent); // false. But why???
至于类的继承(或者更确切地说是JS中的类),情况就不同了:
class Parent {
constructor(property) {
this.property = property;
}
}
class Child extends Parent {
constructor(property) {
super(property);
}
}
const child = new Child("");
console.log(child instanceof Child); // true
console.log(child instanceof Parent); // also true!!!
造成这种差异的原因是什么?是否可以创建子对象,以便正确地将它们识别为父原型的实例(无需借助类)?
【问题讨论】:
-
你的第一个例子没有使用原型继承,这就是原因。
标签: javascript object inheritance