Entity Black
Entity Black

Reputation: 3491

Is instanceOf broken after Object.create?

I tried to do some inheritance with Object.create as I usually do. But few days ago I reallized, that constructor is also the property of prototype, so then my instanced of child appeared like instanced of parent. Well not a big deal, I tried to fix that, here is code snippet:

var Parent = function() {
}

var Child = function() {
    Parent.apply(this, arguments);
}

Child.prototype = Object.create(Parent.prototype);
// now I tried to fix that bad constructor
Child.prototype.constructor = Child;

Everything was fine:

var first = new Child();
first.constructor === Child; // true
first.constructor === Parent; // false

then I find out that:

first instanceof Child; // true
first instanceof Parent; // true - HUH?!?

I mean, this is good, but I dont understand where it happen. Can anybody explain this? Thank you

Upvotes: 1

Views: 268

Answers (1)

Bergi
Bergi

Reputation: 664936

this is good, but I dont understand where it happen. Can anybody explain this?

The instanceof operator does not have anything to do with the .constructor property - it only checks the prototype chain. Which you correctly did set up with Object.create, so that Parent.prototype.isPrototypeOf(first).

Upvotes: 3

Related Questions