Fleegix.org

Arrays and instanceof with iframe

2006-10-27 07:32:00

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 test

myArray 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.


Comments

bobby rulo (2006-10-27)
Matthew, Interesting post. Have you tried doing something like: a instanceof iframe.Array ? Bobby


About

This is the blog for Matthew Eernisse. I currently work at Yammer as a developer, working mostly with JavaScript. All opinions expressed here are my own, not my employer's.

Related

Previous posts

All previous posts ยป

This blog is a GeddyJS application.