简体   繁体   中英

how to check constructor of instance

i created new instance('instance1' and 'instance2') using 'new' keyword. just like this.

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.without 'Child.prototype.constructor = Child'

function Parent() {

}

function Child() {
  Parent.call(this);
}

Child.prototype = new Parent();

var instance2 = new Child();

And i can check the constructor of instance using 'instanceof' keyword.

instance1 instanceof Child  // true
instance1 instanceof Parent // true

this result is make sense, because i clearly wrote 'Child.prototype.constructor = Child;'. so instanceof keyword can find both constructor. BUT

instance2 instanceof Child  // true
instance2 instanceof Parent // true

. but this result is not make sense for me. i expected

instance2 instanceof Child  // false

because i did not write 'Child.prototype.constructor = Child;'.

Why???

instanceof operator looks up if the Constructor.prototype object is present in the Prototype chain ( __proto__ ) of the object being tested.

So in your example:

function Parent() {}

function Child() {
  Parent.call(this);
}

Child.prototype = new Parent();

var instance2 = new Child();    

Since instance2 is constructed from Child() constructor, the __proto__ of instance2 points to the prototype object of Child() constructor ie Child.prototype .

When you test for:

instance2 instanceof Child

instanceof operator will look if Child.prototype object is present in the prototype chain of instance2 , which results in true since instance2 was constructed from Child() constructor.
In other words:

instance2.__proto__ === Child.prototype


Taking your example of second case:

instance2 instanceof Parent

Here also instance2 's prototype chain ie ( __proto__ ) has Parent.prototype object it will evaluate to true. ie

instance2.__proto__.__proto__ === Parent.prototype


Final Note:

instanceof operator works very much like the above conditional checks to test whether an object is an instance of a constructor. The constructor property present on Constructor function's prototype object is never used by instanceof operator while testing.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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