Sunday, August 30, 2009

Whoops, associative arrays? You mean Object?


     Last post I mentioned that extending Array breaks javascript associative arrays. But as Daniel Bodart pointed out and can be confirmed here and here, there's no such thing as an associative array. It's just a javascript object. It's only for historical reasons that Array has been used for this purpose. When I was first reading about javascript I remember reading about arrays and associative arrays and it stuck in my head. I never realised that these were just objects that just happened to be using Array.  
      There is one surprising thing about this though. Calling for a in b on an array or Array.prototype does not reveal length or any of the inbuilt properties or fuctions. 




     Length is missing from the list of properties. And so are all the other predefined properties. But this is true of all Objects. In a similar vein Object.prototype.constructor reveals Object, but dumping everything in Object.prototype does not reveal the constructor property.

     I guess this makes it clearer. Associative arrays being a special javascript construct is some sort of useful fiction that's used as a teaching aid. Once it's discarded you see that adding special methods to Array only breaks a misuse of Array. On reflection my continuing to believe Associative Arrays were a special construct is akin to learning all the laws of physics and still believing in Santa Claus. I guess the question now is, how do you add methods to Object.prototype without breaking the simple hash usage?

No comments:

Post a Comment