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?