How to Subclass an Array (Not Really)

10:27 AM

Update: I don't recommend following the advice in this post. The 5-minute-ago version of my self was hatsy, arrogant, foolish and a bad dinner guest. I recommend the recently updated version of this post from the 1-minute-ago version of my self. He seems to be more well mannered and even keeled--I like him. However, if you're interested in what advice I used to be capable of delivering, please go on.

If you've ever written more than a few lines of JavaScript, you've probably instanced and iterated an Array or two. As you've done this, you may have even thought to yourself, "Gee willikers, wouldn't it be keen to hook a contains() method on the Array prototype to simplify that awful indexOf(val) !== -1 shenanigans?"

You may have even tried to simply extend the native Array prototype. Life would have been grand until you needed your JavaScript to work in IE.

From there, if you're at all like me, you might have thought: "This is friggin' JavaScript! Everything is mutable; everything is extensible! I'll just subclass the native Array type." The subsequent journey through Google would then lead you to believe that the problem of subclassing Array is so hard, so frought with peril, so dangerous that no one could ever do it and do it right.

And if you followed any of the advice that Herr Google had to offer, you would be right. And then you watched Douglas Crockford's On JavaScript series and hit Part III: Function the Ultimate. Suddenly, it becomes much, much simpler.

We now have an array() function which operates just like a plain vanilla, JavaScript Array (push, pop, splice and all intact), addressable by index with a properly functioning length property...and which contains a contains() method.

To do this, we didn't need 'this' or 'new', and we don't have to touch 'prototype' at all if we wanted to interpret 'arguments' differently (though Array.prototype.slice.apply is probably the most efficient way to do it).

This prototypical class model is, in my opinion, much easier to implement, read and debug than any of the blood, sweat and tear infused models suggested around the 'tubes.

As always, your mileage may vary.

You Might Also Like

0 comments

Public Domain. All content published here is released into the PD, except when otherwise indicated. Powered by Blogger.

Peers

Popular Posts

Like us on Facebook

Flickr Images