Javascript Reference
Categories: Operators

javascript Operators instanceof

@March 15, 2008, 1:22 a.m.
instanceof Firefox/Netscape/NN 6 IE 5(Win) ECMA n/a  

  

The instanceof operator lets scripts determine if an object (the left operand) is an instance of a known object (or inherited from the known object). In some ways, this operator is like the typeof operator, but rather than returning a broad object type, an expression with the instanceof operator returns a Boolean value against your test for a more specific object type. In fact, you can query an object against custom objects and, in Netscape 6, W3C DOM tree object prototypes. Whereas the typeof operator on an array returns object, you can find out if an object was instantiated specifically as an array:

myVar instanceof Array
 

Note, however, that if the above expression evaluates to true, so does:

myVar instanceof Object
 

An array is a descendant of the root Object object, and is thus an instance of that root object, as well.

 

In Netscape 6, either or both operands can also be references to DOM prototype objects. Therefore, the following expression is legal and operational in Netscape 6:

document.getElementById("widget") instanceof HTMLDivElement 
 
Example
 
if (theVal instanceof Array) {
    // go ahead and treat theVal as an array
}

Powered by Linode.