20 September 2012

Passing Arrays Between Contexts In Javascript

Today I have found a nasty gotcha that stumped me for some time while creating a snippet of JavaScript which called a function that included an Array as a parameter.

I was trying to call a function on an object bound to the window which contains some utility classes. I created my Array, populated the values and sent it to the function. However, it didn't work as expected. After some head scratching and debugging in Chrome I found that the receiving code was not seeing the Array parameter as an instance of Array. Instead it was seeing it as an object.

After checking my calling code to ensure I was not having a daft moment, and after much trial and error I hit Google. The answer was actually rather obvious once I found it. The problem I was having was that the calling code was in an iframe in my page. When you create an Array you are actually creating a window.Array object. This of course means that the object's prototype is not available to in the window context (i.e. the parent page) and so the receiving function was treating it as an object.

The answer, as I realised while talking to my co-developer, was that in order for the parameter to be seen in the receiving code as an Array, it needed to be declared as new parent.Array(). Once this change was made everything worked as expected.

No comments: