繁体   English   中英

如何检查实例的构造函数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM