Site Navigation

Wednesday, March 26, 2008

bug 181 - can't subclass an Array in IE

Issue: #181
Affects: IE6, IE7, IE8 Beta 1
Fixed In: IE8

MSIE Feedback ID: 334333 (related to the attributes Array)

The #1 rule in OOP (Object Oriented Programing) is that you don't prototype on native objects. This is why many developers do not like the Prototype.js and similar JS Libraries, and where designing for expected behavior of objects is key.

Lets say you want to subclass the Array object, so that you can enjoy using an .each() method on an Array, in browsers before Firefox 3 etc.

No problem, just add this:

Example:

<script type="text/javascript">
var MyArray = function(){
//define your "class"
};
MyArray.prototype = new Array;
//now add your method...
MyArray.prototype.each = function(ref){
//do your magic...
}
</script>


This will work perfectly fine in all browsers, except IE. IE will not update the MyArray instances properly to return the correct length when requested. This of course is rather catastrophic, as it is the only way to know how "big" the array is when iterating over it!

Curious as to why it doesn't work? Well the folks at Microsoft's JScript team let the cat out of the bag and it turns out, that internally it isn't an Array, but rather a HashTable, thus explaining why the performance (pre IE8) was horribly slow, and sub classing just wasn't an option.



Known Workarounds: None. Well, this isn't entirely true. If you "steal" an array from another frame, you can cater it to your needs, but it gets quite involved and it still isn't a true sublass (e.g. you can't re-subclass it) See Dean Edwards Blog post here for more info.


Related Issues: None.

Bug/Site Feedback |
Submit a bug