The instanceof
operator
The instanceof
allows to check if the object is created by given constructor:
function Rabbit() { } var rabbit = new Rabbit alert(rabbit instanceof Rabbit) // true
The instanceof
has nothing to do with the constructor
property. It follows the __proto__
chain instead.
The logic behind obj instanceof F
:
- Get
obj.__proto__
- Compare
obj.__proto__
againstF.prototype
- If no match then set temporarily
obj = obj.__proto__
and repeat step 2 until either match is found or the chain ends.
In the example above, the match is found at the first step, because: rabbit.__proto__ == Rabbit.prototype
.
A deeper example:
function Rabbit() { } var rabbit = new Rabbit alert(rabbit instanceof Object) // true
Here, the match is found at rabbit.__proto__.__proto__ == Object.prototype
.
Note that the comparison only uses __proto__
and prototype
, the function object itself isn’t involved.
When instanceof
lies
The instanceof
lies when a value comes from another frame or iframe.
For example, an array which came from an iframe is instanceof Array
in that iframe
. Every frame or iframe has it’s own window
object and the hierarchy.
Usually, the problem arises with native objects, so the solution using <a href="/tutorial/type-detection">[Class]]
works. It is described in the article [.
Summary
obj instanceof Func
checks if theobj
is a result ofnew Func
. The check is performed by walking the__proto__
chain, so the inheritance is supported:
var arr = [] alert(arr instanceof Array) // true alert(arr instanceof Object) // true
- The
instanceOf
lies when an object comes from another window(or frame). The guaranteed-to-work replacement for native objects is checking<a href="/tutorial/type-detection">[Class]]
, see [.