company-logo

jQuery vs. Prototype: OO JavaScript with or without training wheels

After brushing up on jQuery via a little light reading, I’ve started to play with the framework in code. I’m demoing a scrolling news ticker and decided to write it using jQuery and its Interface plug-in. Future iterations will probably include the history and easing plug-ins, too. In the meantime, though, it’s been two steps forward, one step back. I really dig the elegance of the jQuery API and its concise method-chaining. But there’s one integral element of the Prototype/Script.aculo.us framework that I miss: The Class object and the OOP training wheels it provides.

For developers like myself – long-time UI folks who have used JavaScript’s Object datatype for years but lack significant experience writing in a strongly typed, truly object-oriented language like Java – Prototype has been a revelation. It doesn’t enforce OOP principles, but it encourages them. And its source code is like a Rosetta Stone for how to implement them in the dynamically typed, prototype-based world of JavaScript.

There’s been lots of discussion over the past year about the deficiencies of Prototype’s inheritance scheme. A lot of the syntax is ugly, and Object.extend is easy to overuse or misuse. The new 1.6.0 release candidate appears to address some of those weaknesses by augmenting the Class object’s API. Regardless of your position on this debate, though, it’s hard to ignore the fact that Prototype has helped a lot of front-end folks improve their half-assed understanding of OOP. Personally, I wouldn’t even be in a position to follow the discussion if I hadn’t spent the last 18 months or so writing Prototype-backed JS classes. Thanks to the patterns to which this library has exposed me, my grasp of JavaScript – and of software engineering in general – has grown by leaps and bounds.

Once I started using a different library, though, Class.create was suddenly useless. I had to figure out different inheritance and encapsulation strategies. The training wheels were off, and I had to find my own of balance. My first hurdle was figuring out how to organize my jQuery procedures into reusable methods. I felt totally adrift without the built-in ability to bind functions to their execution environment; the this keyword was always assigned to a DOM node. I thought about simply porting Prototype’s Function.bind and Function.bindAsEventListener methods, but that seemed at odds with the design of jQuery’s own API. Finally, I turned to Douglas Crockford‘s module pattern for JavaScript. Now I had a new way to organize my objects and methods in a reusable way that worked well with jQuery. By defining private methods inside of a closure, I could access those methods with simple function calls, no binding necessary. As with Prototype, a whole new world opened up.
   

A lot of developers worry that Ajax frameworks make for lazy programmers, but in my experience the opposite is true. Each new design pattern or framework that I play with teaches me new approaches to JavaScript and OOP in general. Folks coming at UI development from, say, a C++ background may want a framework that enables a well-defined inheritance model. But OOP scaffolding is a separate concern from Ajax and DOM tools. Prototype provides both, while the base jQuery library provides only the latter. Still, somebody could easily write an OO plugin for jQuery – or several of them, each implementing a different inheritance model.

Simon Williamson’s recent post on jQuery for JavaScript programmers does a good job of explaining how jQuery encourages good OOP techniques. The walled-off namespacing represents a different conceptual model from Prototype’s. Until you understand both, it’s difficult to see all the strenghts and weaknesses of either. As with other tool, the key to these frameworks is learning what tricks and tradeoffs each one supplies, and why. Up next: YUI and Ext.

Related Services:
Ajax Rich Internet Applications, Custom Software Development

  1. Sebastian Werner Reply

    I like the qooxdoo way of OO. They also have features like Interfaces (Java) and Mixins (Ruby). Looks like a really advanved solution, but the implementation is quite easy to understand. Have a look yourself at: http://qooxdoo.org/documentation/0.7/class_declaration

  2. Isaac Z. Schlueter Reply

    Once I started using a different library, though, Class.create was suddenly useless. I had to figure out different inheritance and encapsulation strategies.

    Yes, exactly. Prototype (and jQuery, to a lesser extent) attempts to rewrite Javascript and turn it into something else. Javascript is not, fundamentally, a C-style language. It’s the ugly duckling of the Lisp/Scheme/Haskell crowd. Turning it into Ruby or Java is a misguided notion that short-circuits what Javascript is fundamentally all about.

    Doug Crockford’s “Module Pattern” is just what Javascript gives you for free. Like most things in YUI, it’s just showing off effective use of the language, rather than showing off how the language can be transformed into something different.

    It’s interesting that Javascript is the only language to suffer this sort of abuse on a regular basis. You don’t see Java frameworks that aim to make it more like Ruby, or C++ frameworks that emulate Ada. I think Javascript got a bad rap–guilt by association with flickering doodads in the 1990s, perhaps. For whatever reason, it seems that the software development crowd seems to be largely of the opinion that Javascript is too hard, badly designed, and not “really” OOP, but at least it can be transformed into a “real” language with the proper framework.

    I wrote about this a few weeks ago in response to a post by Matt Snider:
    http://foohack.com/?p=24

  3. Matthew Smith Reply

    I have a new framework – JLJ (Just Learn JavaScript).

  4. mark Reply

    What about mootools’ class structure? Have you tried out that library?

  5. Jim Reply

    > Simon Williamson’s recent post

    That’s “Willison”.

  6. speedmax Reply

    You should give mootools a try.

    for community support jquery/prototype wins

    but for elegance Object orientation in javascript, and the overall design philosophy. Mootools is far more cleaner

    at the end of the day, it is just depends on how your brain works, mootools inherit many to all prototype goodness.

    for OO purist/software design freak like myself, mootools is additive and inspiring

  7. WNAS Reply

    prototype and jQuery

    a small piece that compares the two frameworks, with some nice links to follow..

  8. Andrew Reply

    While it is important to understand the concepts behind any programming language, as well as frameworks that are being used, it would be a ridiculous waste of resources to rewrite the components that open source javascript frameworks are now able to provide. By using a good, solid framework that extends javascript, we as developers are able to provide more robust solutions in less time. Additionally, we are able to focus our time on ensuring that we are meeting the requirements and needs of our customers, rather than spending an unnecessary amount of time in the weeds trying to reinvent the wheel.

  9. Andrew Reply

    While it is important to understand the concepts behind any programming language, as well as frameworks that are being used, it would be a ridiculous waste of resources to rewrite the components that open source javascript frameworks are now able to provide. By using a good, solid framework that extends javascript, we as developers are able to provide more robust solutions in less time. Additionally, we are able to focus our time on ensuring that we are meeting the requirements and needs of our customers, rather than spending an unnecessary amount of time in the weeds trying to reinvent the wheel.

  10. Jeff Reply

    I agree with Andrew; for far too long, it has taken way too long to push out good Ajax GUI, and componentization is here to stay folks; and the thing that makes Jquery really exciting is that you get the plugin library and EXT to work with for free, as well as the Jquery UI widgets.

    That’s 3 widget sets, and I love widgets. Almost anything I do, I start with an existing widget, and extend it a bit to do all the things I need. Works great, and often I don’t even have to touch it, already does what I need entirely, even with the world-class, super-fussy UI designer I work with..

    Prototype can use Ext too, but I have seen nothing in the prototype arena that can compare to the jquery plugin library. The Jquery plugin lib appears to me, to be growing exponentially. The Ajax community is really coming together around Jquery.

    Scriptaculous does not even come close as far as I can tell…
    Am I missing something?

  11. Tyson Reply

    Could you elaborate on how you found “a new way to organize my objects and methods in a reusable way that worked well with jQuery. By defining private methods inside of a closure, I could access those methods with simple function calls, no binding necessary. As with Prototype, a whole new world opened up.”
    I still haven’t found a way to have a Jquery callback function wrapped in a reusable custom Javascript class that allows me to read/write the class’ private variables.
    Example:
    customClass = function () {
    this.doJquery = function (){
    $(“element”).click(function (){
    this.foo = bar; // wanting to set myObj.foo
    x = this.foo; // wanting to get myObj.foo
    });
    }
    }
    myObj = new customClass();
    myObj.doJquery();
    y = myObj.foo; // doesn’t work

  12. Brian Dillard Reply

    It looks like Tyson asked this same question elsewhere, and already received an answer in the comments:

    http://remysharp.com/2007/04/12/jquerys-this-demystified/

    The only thing I’d add is that, by convention, when creating a custom class, I use that to alias this:

    var myObject = function() {
    var that = this;
    }

    I then use that within callbacks and interior functions to reference the top-level object:

    var myObject = function() {
    var that = this;
    this.foo = “foo!”;
    var innerFunction = function() {
    alert(that.foo);
    }
    this.publicMethod = function() {
    innerFunction();
    }
    }

    This convention, which helps obviate the need for Prototype-style Function.bind(), comes from Douglas Crockford.

  13. Michael Lee Reply

    Great article Brian!

    On the topic of OO JavaScript, have you looked at or heard of Ajile – http://ajile.iskitz.com/.

    It’s a Namespacing library for JavaScript that extends the language with missing functionality without imposing new ways of writing code. Most OO developers already understand the power and convenience of namespacing, but it’s a concept that’s only now emerging as needed for JavaScript in this age of mashups and ajax mania.

    Ajile’s namespacing and accompanying Import, ImportAs, Include, and Load directives (mimicked via functions) also support the OO Model View Controller (MVC) design pattern by automating the linkage and inclusion of JavaScript logic to HTML views. That allows developers to safely separate their server-side business logic from their front-end views, view manipulation, and client-to-server data transfer.

    I’m interested to hear what you have to say about it and the concepts it introduces to the oh so flexible JavaScript language :-)

  14. Elijah Reply

    “A lot of developers worry that Ajax frameworks make for lazy programmers, but in my experience the opposite is true.”

    I agree with this statement, and to take it out of context for a second (OOP or not) is this not the direction we are taking? Allow the *competent* developer knowledgeably jump from one implementation to another without a glance to the documentation. As well as making it increasingly more efficient to develop these applications that keep food on the table.

    It would seem as though we are moving in this direction albeit ‘slowly but surely’. I can hardly wait for the day when open source unifies :)

    Great post, thanks.

  15. A Reply

    Trying to do the classic OOP style using jQuery is like trying to peg a round hole with a square cover.

    jQuery embraces a functional style which is closer to home in a language like JS which has its roots in Scheme.

    Java/C++ style can be done but is a force fit.

  16. Caligula Reply

    > You don’t see Java frameworks that aim to make it more like Ruby [...]

    Sure you do, it’s just that Java makes it extremely difficult, by working actively against the developer.

    JavaScript sees these attempts because it *allows you to make them*.

  17. Ódýr vefhýsing Reply

    JavaScript is prototype-based scripting language. Use it for what it was build for until ECMA 4 is in place. This, however, is a great article. Cheers.

  18. Boyan Kostadinov Reply

    Here are a couple of options:

    http://ejohn.org/blog/simple-javascript-inheritance

    and a plugin port of Class.Create:

    http://plugins.jquery.com/project/HJS

Leave a Reply

*

captcha *