Friday, August 10, 2012

The perils of instanceof in Javascript

I was having one of those Internet Explorer moments in Javascript, when I wanted to use Array.isArray and I couldn't because it was IE8. So, I thought, I would create my own isArray function and attach it to Array, so that it works cross browser. The issue now was how do I detect if an object in Javascript is an Array.

The instanceOf operator came to mind immediately. After all, don't you do the same thing in C#, compare if an object "is" something? Luckily for me, I checked the Internet and reached the faithful StackOverflow with an answer. The interesting bit was explaining why instanceOf would not work for all cases and that is that objects that cross the frame boundaries have their own version of class.

Let's say that you have two pages and one if having the other in an iframe. Let's call them innovatively testParent and testChild. If you create an array instance in testChild like x=new Array(); or x=[];, then the result of x instanceOf Array will be true in testChild, but false in testParent. That's because the Array in one page is different from Array in the other. And, damn it, it makes sense, too. Imagine you did what I did and added a function to the Array class. Would that class be the same as the Array in the iframe, without the function? What if I decide to add

So, bottom line: in Javascript, instanceOf will not work in any meaningful way across frame boundaries.

Oh, and just so you do have a good way to check if an object is and array, do this:
var strArray=Object.prototype.toString(new Array());
Array.isArray=function(obj) {
  return Object.prototype.toString(obj)==strArray;


Andrei Rinea said...

How can you not "love" javascript... this is one of the many reasons I didn't go to much (or at all) in depth in javrascript (typo intended).

Siderite said...

I can't agree with you. I think that the simplicity and flexibility of Javascript have made it a solid and powerful language. Its design is also rather original compared to any other mainstream programming language.

I would say that I prefer Javascript as it is rather than a myriad of proprietary and closed languages that each browser decides to promote or not.