OdeToCode IC Logo

Of .prototype and function()

Sunday, June 20, 2010

Years ago, when I began to take JavaScript seriously, I thought prototypical inheritance was marvelous.

Accordian = function (element, isOpen) {
    this.element = element;
    this.isOpen = isOpen;

Accordian.prototype = {
    open: function () {
        // ...

    close: function (value) {
        // ...

It took some time, but eventually I wondered if using an OOP approach in page scripts was like using cranes to tow compact cars.

Tow truck overkill by Dave Pinn.

It turns out the developer working on a single page doesn't need to build or consume big, strong abstractions for programming "in the large". It's become clear over the last several years that function() is the right-sized abstraction.  You find the DOM element and I'll tell you how it should behave. You wire up the click event and I'll tell you what to do when it's clicked. Give me functions that figure out the hard stuff and let me fill in the details. 

$(".header").click(function () {
    $(".content", this).slideToggle();

This doesn't mean there isn't value in modifying prototypes, but I think the prototype approach has a greater value in building libraries, APIs, and core infrastructure pieces. For page scripts the ability to program against a functional API allows a developer to separate concerns in a concise manner, and compose complex behaviors using smaller pieces of raw material. Sometimes these pieces of functionality even carry state, but the state is wholly encapsulated in a closure.

But will it hold?

There is a lot of change on the horizon as features like background processing, local storage, and a drawing canvas will come with the browser for free. Will the language and paradigms support programming in the large?

What do you think?

Gravatar varun Monday, June 21, 2010
generally when I have a single page to code and very few/limited features to handle,I use light weight abstractions.

I guess no point going all crazy over oop unless I code huge frameworks eg:openlayers.

Gravatar Jeremy D. Miller Monday, June 21, 2010
I'm going to partially disagree. The prototype based inheritance I've never found very useful, but I've found plenty of usage for old fashioned OOP with JavaScript on even just moderately complex pages. I think it's just another case of favoring composition (with either objects or functions) over inheritance.
Gravatar Elijah Manor Tuesday, June 22, 2010
Yeah, I don't use prototypical inheritance either, but I find the use of the Revealing Module Pattern to keep my JavaScript & jQuery code much more maintainable & easier to test than when I went without it
Gravatar Kenny Wednesday, June 23, 2010
The revealing Module Patterns is fantastic and has finally led to better Javascript in our shop. Love it!
Comments are closed.