Breaking instanceof in Javascript

That’s right, this afternoon I figured out how to break instanceof in Javascript. Since I don’t use it often, I figured it worked just like it does in PHP. Basically it does, with one major caveat. Mozilla’s javascript reference gives this definition of the instanceof operator:

Use instanceof when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.

Earlier today, I was trying to pass data from a child window to its parent window. From there, the parent window used JSON to encode the data ….. but it never got encoded. Upon further investigation, I saw that JSON used the instanceof operator to determine if an object was an Array. I created these test pages to confirm my results:


function foobar(value){
  alert(value instanceof Array);
  alert(value instanceof child_window.Array);
var child_window ='child.html');


    window.opener.foobar(new Array(1,2,3));

The first alert is false, while the second one is true.

In Javascript, all objects are “owned” at the root level by the window. Since the window is different for child windows, it makes sense that instanceof would break.

For most small applications, this doesn’t matter. But for Webmail, it does. I have a couple ideas for a good workaround, but nothing set in stone yet.