JavaScript Object Method Chaining: useful?

Hexagon Theory picture Hexagon Theory · Mar 2, 2009 · Viewed 14.8k times · Source

So... messing around in JavaScript with an idea that's new to me, having methods of an Object return the Object of which they are methods; this then leads to chainability. My question, then: how can this be useful? I threw this together to test the fundamental workings:

<script>
MathChain = function()
 {
    this.pass = function()
     {
        this.multiply = eval(arguments.join('*'));
        this.add = eval(arguments.join('+'));
        return this;
     }
 }

m = new MathChain().pass(5, 10, 20).multiply; // 1000
a = new MathChain().pass(5, 10, 20).add;      // 35
</script>

That's obviously not a viciously efficient instance in which one would use this concept, so could you point me to something that does do so properly (aside from jQuery, please)?

Answer

jonstjohn picture jonstjohn · Mar 2, 2009

Well, here is a not very real-world applicable example, but I think you'll get the idea. If allows you to do a number of different operations on an object, and provides convenience.

var truck = function() {

    this.turnLeft = function {

       // turn left
       return this;

    }

    this.turnRight = function {

       // turn right
       return this;

    }

    this.goReallyFast = function {

       // go fast!
       return this;

    }

};

// My get-away plan
var myTruck = new truck();
myTruck.turnLeft().turnRight().goReallyFast();