Prototypify - safe javascripting with Prototype

A month or so we started a discussion here about how Prototype might work in CNET’s front end environment. Several issues came up including it’s file size (55K for the latest version) but also the fact that it extends the prototype objects of Array, String, and Object in ways that may (and have) caused problems with our advertiser’s own code. It’s unacceptable to expect them to re-author their scripts to accomodate our shortcuts, and it’s unacceptable to expect tech-prod and ad-dev to regress all the ads on our network.

I authored a version of prototype.lite (part of the moo.fx library) that removed these extentions from the Array and Object types. When writing code you could wrap your arrays and objects with $A() and get allt he prototype action (i.e. $A(myArray).each) without breaking any 3rd party code. My version also includes the event management of Prototype and clocks in at just under 8K (which is some super savings compared to the full Prototype library).

Still this creates a fork in the Prototype.lite code and it doesn’t fix things for the full library of Prototype, nor does it fix 3rd party libaries like moo.fx and Scriptaculous. We don’t want to re-write all those things every time we use them.

So I hired a contractor - a friend of mine whose code kung fu far surpasses my own - to craft a solution for us. Enter Prototypifiy (3Kb):

The Package is designed permit safe use of the Prototype javascript framework along side arbitrary 3rd party scripts (i.e, advertisements). The Prototype package adds many utility functions to the native javascript Array, String, and Number classes. Due to some peculiarities of the javascript language, these additions will show up when ever a script tries to iterate (using the “for x in l” syntax) over the values in any instance of an Array (or over the characters in a String). This may have dire consequences for an unsuspecting script.

One solution would be to simply discard the Prototype package, but, in addition to the loss of a powerful set of tools, this would also eliminate other packages like Script.acoul.us and Moo.fx. Disposing of the third party code is also undesirable, because it’s often what’s paying the bills.

Prototypify solves this dilemma by removing prototype functions by default. It then allows the programmer to proxy the functions that are expecting Prototype functionality so that the functions are restored prior to execution and removed again when execution completes.

see full documentation & examples
get the code

I’m very much interested in what people think of it. I’d like to suggest three coarses of action:

1) an evaluation of this code by anyone using prototype

2) dependent on #1, a re-authoring of any code that has such dependencies (implementation shouldn’t be too difficult; see documentation)

3) releasing this library as open source

Leave a Reply

You must be logged in to post a comment.