1

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

Danilo Valente
  • 11,270
  • 8
  • 53
  • 67
Entity Black
  • 3,401
  • 2
  • 23
  • 38
  • I think it's because `Parent` is a part of `first`'s prototype chain. – Johan Feb 20 '14 at 13:42
  • If Cat inherits from Animal, pussnboots = new Cat() is also an instance of Animal. – Tibos Feb 20 '14 at 13:45
  • possible duplicate of [JavaScript inheritance and the constructor property](http://stackoverflow.com/questions/8093057/javascript-inheritance-and-the-constructor-property) – Aadit M Shah Feb 20 '14 at 13:55

1 Answers1

3

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).

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • I have another question. Shouldnt be Object.prototype.constructor {writable : false} or {configurable : false} or both? I dont understand, why would anybody want to change this property... – Entity Black Feb 24 '14 at 16:19
  • 1
    @Windkiller: It's just [not specified](http://es5.github.io/#x15.2.4). There are hardly good reasons for overwriting built-in objects, but it could be useful if you wanted to [wrap the `Object` constructor](http://stackoverflow.com/a/21243884/1048572). – Bergi Feb 24 '14 at 17:54