Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instanceof - javascript inconsistency in Object-Oriented javascript by Stoyan Stefanov

In Stoyan Stefanov's book Object-Oriented javascript, on page 103 he has the following. However when I try this, I get a different result with h instanceof Object. Am I missing something, has something in JS changed since or is this an error in the book.

>>> function Hero(){}
>>> var h = new Hero();
>>> var o = {};
>>> h instanceof Hero;
true
>>> h instanceof Object;
false //true in Google Chrome
>>> o instanceof Object;
true 

Book excerpt

Google Chrome output

like image 304
KingKongFrog Avatar asked Oct 20 '22 19:10

KingKongFrog


1 Answers

If that's what the book says, then the book is incorrect. (And searching the book content in Amazon.com confirms the error.)

Your true result that you get in Google Chrome is the correct result.

While the h object inherits from the .prototype on the Hero function, that .prototype inherits from the .prototype on the Object function. This means that h inherits both from Hero.prototype and Object.prototype, and is considered an instance of both constructors.

The only way it wouldn't be would be if Hero.prototype was an object that did not inherit from Object.prototype. But in that example, it uses the default object, so it does indeed inherit.

like image 163
cookie monster Avatar answered Oct 27 '22 09:10

cookie monster