1

JavaScript instanceof operator uses a prototype chain to return the type of object.

Let say, If i have below hierarchy.

Rabit->Animal->Object->Null

Now if i wanted to know any instance is actually a rabit or animal or Object, I can not do this.

if (rabbitObj instance of Animal) // true
if (rabbitObj instance of Rabit) // true
if (rabbitObj instance of Object) // true

How can get rabbitObj is actually a Rabbit.

How i can get actual type of instance, instead of following prototypical chain.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Pavan Tiwari
  • 3,077
  • 3
  • 31
  • 71
  • 3
    "Actually" a Rabbit? You probably really mean this: http://stackoverflow.com/a/1249554/438992 – Dave Newton Jun 15 '16 at 14:39
  • Not getting it, it seems that you answered your own question -> if (rabbitObj instance of Rabit) // true. This should answer your question. – Guillermo Jun 15 '16 at 14:41
  • Possible duplicate of [How do I get the name of an object's type in JavaScript?](http://stackoverflow.com/questions/332422/how-do-i-get-the-name-of-an-objects-type-in-javascript) – Annihlator Jun 15 '16 at 14:42
  • 1
    You would just have to check them in the order of the hierarchy. If it tests true for `rabbitObj instanceof Rabit`, then it is obviously a rabbit. Whereas another animal `squirrelObj = new Squirrel();` would not test true for this. Both would test true for the `rabbitObj instanceof Animal` condition though. – shamsup Jun 15 '16 at 14:46

1 Answers1

0

You are trying to use JavaScript's delegation behavior as class based languages inheritance but they are different things. In JavaScript you must think in terms of objects and their prototypes, and understand how the delegation can work for you to achieve what you are looking for instead of the inheritance.

Read more about the prototype and delegation systems in the You Don't Know JS: this & Object Prototypes book, specifically the Prototypes chapter.

David Gomez
  • 2,762
  • 2
  • 18
  • 28