One of the coolest “models” to emerge from the JavaScript world in recent times is definitely “prototypal chainability” – a made up term coined by me to describe the indescribable model you see being used in libraries such as jQuery. I’m talking about that which enables you to chain separate method calls (of the same prototype) one after another; each call is made on the same instance. It’s like this:

$('#boo').filter(':funny').addClass('funny').css('color', 'red').show();

You might just call it “prototypal inheritance” and be done with it, but I would argue that it goes one step further, by making everything “chainable”!

If you wanted to create your own library with a similar style of notation then you’ll be happy to hear that doing so is incredibly easy. Here are the steps involved:

  1. Create a constructor.
  2. Wrap it in something pretty (e.g. $).
  3. Add methods to the constructor’s prototype.
  4. Always return an instance of the constructor from each method.

Here’s an example, our “pretty wrapper” is ‘X’:

(function(){
 
    // Create it in a closure so we don't reveal the constructor:
 
    // The constructor:
    function XConstructor( args ) {
        // Minor point: convert arguments to real array:
        this.args = Array.prototype.slice.call( args );
        return this;
    }
 
    // The wrapper:
    function X() {
        return new XConstructor(arguments);
    }
 
    // Add some methods:
    XConstructor.prototype = {
        logArguments : function() {
            console.log( this.args );
            // Return the instance:
            return this;
        },
        addArgument : function( newArg ) {
            this.args[this.args.length] = newArg;
            return this;
        },
        removeArgument : function( index ) {
            this.args.splice( index, 1 );
            return this;
        }
    };
 
    // Reveal X to the global object.
    // Window is the global object in most situations:
    window.X = X;
 
})();

And now, we can do something like this:

X('apple', 'orange', 'pear')
    .logArguments()
    .addArgument('banana')
    .addArgument('melon')
    .removeArgument(3);
 
// Or, without the indentation:
X('apple', 'orange', 'pear').logArguments().addArgument('banana').addArgument('melon').removeArgument(3);

For all intents and purposes, this is how jQuery’s “chainability” works!

Go fourth and create prototypal chains!