Arrays and instanceof with iframe
Posted by mde [ Fri, 27 Oct 2006 04:32:00 GMT ]
When is an Array not an Array? When it's off in another window, apparently.
I've just found that when you reference a JavaScript Array object in another window (in this case, in an iframe), the normal (myArray instanceof Array) test fails. Googling led me to some commentary from Professor Crockford on the whys and wherefores of this weird behavior:
When you say 'Array', you are talking about 'window.Array'. 'window' is the browser's context object, and you get one per page (or frame). All of the arrays created within a context will have their constructor property set to 'window.Array'.
An array created in a different context has a different window.Array, so your testmyArray instanceof Array
fails. The ECMAScript standard does not discuss multiple contexts, even though virtually all implementations support them. The ECMAScript standard also fails to provide a reliable technique for testing the type of arrays.
Yeah, the typeof value for an Array is just the bland ol' 'Object.' Looks like if you don't care about Safari you can test for the presence of the word 'Array' in .constructor.toString() of the object in question. Firefox and IE will acknowledge that, yes, this thing is an Array -- but Safari designates the constructor method simply as "(Internal Function)." Nice, minimalist design -- much like a one-button mouse. And about as useful.
Crockford's suggestion for winnowing out Arrays from other types of Objects is to check for a well-known Array method like sort in the object. That seems pretty hacky, and in my case all I was trying to do was JSONize the Array -- so it was simple enough to do the serialization in the window with the Array, and reference that string value from the other.