我使用“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;'。
为什么???
最佳答案
instanceof
运算符查找 Constructor.prototype
对象是否存在于被测试对象的 Prototype 链 (__proto__
) 中。
所以在你的例子中:
function Parent() {}
function Child() {
Parent.call(this);
}
Child.prototype = new Parent();
var instance2 = new Child();
由于 instance2
是由 Child()
构造函数构造的,因此 instance2
的 __proto__
指向原型(prototype)对象Child()
构造函数,即 Child.prototype
。
当您测试时:
instance2 instanceof Child
instanceof
运算符将查看 Child.prototype
对象是否存在于 instance2
的原型(prototype)链中,结果为 true,因为 instance2
由 Child()
构造函数构造。
换句话说:
instance2.__proto__ === Child.prototype
以第二种情况为例:
instance2 instanceof Parent
这里还有 instance2
的原型(prototype)链,即 (__proto__
) 具有 Parent.prototype
对象,它将评估为 true。即
instance2.__proto__.__proto__ === Parent.prototype
最后说明:
instanceof
运算符的工作方式与上面的条件检查非常相似,用于测试对象是否是构造函数的实例。测试时,instanceof
运算符永远不会使用构造函数的 prototype
对象上存在的 constructor
属性。
希望这有帮助。
关于javascript - 如何检查实例的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44380901/