News Archive
Related Articles
PhpRiot Newsletter
Your Email Address:

More information

My gripe with Prototype

Note: This article was originally published at Planet PHP on 12 January 2011.
Planet PHP

Many of you might already know this, but I wanted to point out why I think using the Prototype Javascript library is a bad idea. The biggest problem is actually highlighted in it's name: it changes many of the prototypes of core javascript types.

You might have realized this before, when you tried to 'for(in in arr)' and came across many of the extra functions prototype added. (and you should have realized at this point this wasn't the proper way to loop through an array anyway.).

This is a big difference with other established libraries such as jQuery. If you want to use any of the jQuery functionality, you're expected need to wrap other types in a jQuery object, for example:

  1. var myElem = $(myDomNode);

This augments the underlying variable with jQuery functionality. Besides the '$' (which can be turned off), jQuery pretty much keeps all it's hands off your global namespace

Same with YUI. All the functionality is imported through the YUI object:

  1. YUI().use('node-base', function(Y) {
  2. A
  3. Y.on("domready", function() { console.log('ready!'); });
  4. A
  5. });

This is a stark contrast with Prototype. As soon as you include it, it changes basic types such as strings, arrays and numbers. An example:

  1. alert([1, 2, 3].toJSON()); // outputs "[1, 2, 3]"

While from an API perspective, this seems quite nice and by far the simplest. Prototype provides these handy methods close to where you need them.

This has one devastating effect though. It violates the holy "don't pollute the global namespace" rule. In an isolated environment this will work fine, but as soon as you work on an application that includes scripts from different sources or libraries these scripts are now also affected by prototypes changes to core types. In a "mash-up era" it's just not feasible to assume you'll be working in an isolated, sterile environment forever.

My latest example of having to hunt down what prototype feature caused a stir, was when I tried to use the JSON.stringify function. This is a fairly new feature, added by all the modern browsers.

Whenever stringify comes across an object that has a toJSON() method, it will call it. This allows objects to specify their own 'json representation' to for example filter out 'private properties'.


  1. var test = {
  2. A
  3. prop1: 'val1',
  4. A
  5. privateProp: 'hidden',
  6. A

Truncated by Planet PHP, read more at the original (another 4716 bytes)