【问题标题】:how to check constructor of instance如何检查实例的构造函数
【发布时间】: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


【解决方案1】:

instanceof 运算符查找 Constructor.prototype 对象是否存在于被测试对象的原型链 (__proto__) 中。

所以在你的例子中:

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() 构造函数构造的,所以结果为 true。
换句话说:

instance2.__proto__ === Child.prototype


以第二种情况为例:

instance2 instanceof Parent

这里还有instance2 的原型链,即(__proto__) 有Parent.prototype 对象,它将评估为真。即

instance2.__proto__.__proto__ === Parent.prototype


最后说明:

instanceof 运算符的工作方式与上述条件检查非常相似,用于测试对象是否是构造函数的实例。 instanceof 运算符在测试时从不使用 Constructor 函数的 prototype 对象上的 constructor 属性。

希望这会有所帮助。

【讨论】:

  • 谢谢,但我还是不清楚。 instance2.__proto__ 返回“父”,Child.prototype 也返回“父”。所以我可以理解 instance2 与“Parent”相关联,但我认为“instance2”和“Child”构造函数之间没有联系。但instance2 instanceof Child 返回“真”。如何知道 instance2 与 Child 的链接。
猜你喜欢
  • 2021-04-28
  • 2012-09-19
  • 1970-01-01
  • 2011-04-19
  • 2013-03-05
  • 2015-10-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-24
相关资源
最近更新 更多