javascript - 如何检查实例的构造函数

标签 javascript constructor instanceof

我使用“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,因为 instance2Child() 构造函数构造。
换句话说:

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/

相关文章:

java - 创建许多对象类型/类只是为了使用 instanceof

javascript - 为 json 数组中的每个对象创建一个列表

javascript - 值(value)观比较

javascript - 当我单击编辑表单时, Angular 自动填充创建表单的问题

javascript - JS ES5 面向对象 : private instance member via get/set in constructor

PHP 命名空间和构造函数问题

出现错误的Java代码

javascript - JavaScript 中 typeof 和 instanceof 的区别

javascript - 范围链查找与原型(prototype)查找 - 哪个是什么时候

Java-instanceof 的替代品?