Use chained method calls

Libraries like jQuery support chained method calls. This allows you to run multiple different operations at once. For example: <p/> $("someSelector").addClass("cool").appendTo("somethingElse"); <p/> In order to support this your methods need to perform their particular action but then return it's own API again to the caller. In the example below, the Cyclone object supports methods spin, to, with, and start. Notice how spin, to, and with return pointers to the API such that you can chain them as you see it.

var Cyclone = function (name) { = name;

Cyclone.prototype.spin = function () {
    var cycloneOptions = {};

    var start = function () {

    var withStuff = function (debris) {
        cycloneOptions.debris = debris;
        return {
            start: start

    var to = function (location) {
        cycloneOptions.location = location;
        return {
            start: start,
            withStuff: withStuff

    return {
        to: to

Cyclone.prototype.move = function (options) {
    // Move the cyclone with the given options

var marmaduke = new Cyclone('Marmaduke');
marmaduke.spin().to('Japan').start();  // A standard typhoon

var nigel = new Cyclone('Nigel');
nigel.spin().to('Japan').withStuff('Haddock').start();  // A typhoon loaded with dead fish
Published: 5/2/2014
Author: Steve Brownlee
Tags: misc
comments powered by Disqus