【发布时间】:2017-11-06 22:23:23
【问题描述】:
我使用“new”关键字创建了新实例(“instance1”和“instance2”)。就这样。
1.with 'Child.prototype.constructor = Child'
function Parent() {
}
function Child() {
Parent.call(this);
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var instance1 = new Child();
2.没有'Child.prototype.constructor = Child'
function Parent() {
}
function Child() {
Parent.call(this);
}
Child.prototype = new Parent();
var instance2 = new Child();
我可以使用'instanceof'关键字检查实例的构造函数。
instance1 instanceof Child // true
instance1 instanceof Parent // true
这个结果是有道理的,因为我清楚地写了'Child.prototype.constructor = Child;'。所以 instanceof 关键字可以找到这两个构造函数。但是
instance2 instanceof Child // true
instance2 instanceof Parent // true
。 但这个结果对我来说没有意义。我期待
instance2 instanceof Child // false
因为我没有写“Child.prototype.constructor = Child;”。
为什么???
【问题讨论】:
标签: javascript constructor instanceof