[英]how to check constructor of instance
我使用“ 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
运算符查找被测试对象的Prototype链( __proto__
)中是否存在Constructor.prototype
对象。
因此,在您的示例中:
function Parent() {}
function Child() {
Parent.call(this);
}
Child.prototype = new Parent();
var instance2 = new Child();
由于instance2
是从Child()
构造函数构造的,因此instance2
的__proto__
指向Child()
构造函数的原型对象,即Child.prototype
。
当您测试:
instance2 instanceof Child
instanceof
操作者会看如果Child.prototype
对象存在于的原型链instance2
,因为这会导致真正instance2
从构造Child()
的构造。
换一种说法:
instance2.__proto__ === Child.prototype
以第二种情况为例:
instance2 instanceof Parent
在这里, instance2
的原型链(即( __proto__
))也具有Parent.prototype
对象,它将评估为true。 即
instance2.__proto__.__proto__ === Parent.prototype
最后说明:
instanceof
运算符的工作原理非常类似于上述条件检查,以测试对象是否为构造函数的实例。 该constructor
出现在构造函数的性质prototype
对象从不使用instanceof
而测试操作。
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.