Chaining JavaScript

One of my favorite JavaScriptthings is the ability to chain things together.

Consider this function, where the methods return the instance itself;

var myBox = function () {

var self = this, _height, _width;

self.setHeight = function (height) {

_height = height;

return self;

};

self.setWidth = function (width) {

_width = width;

return self;

};

self.getSize = function () {

return _width * _height;

};

return self;

}

We can call it, chaining together multiple actions.

Logger.log (

new myBox()

.setHeight(20)

.setWidth(30)

.getSize());

In my opinion (some would disagree), this is more readable than

var b = new myBox();

b.setHeight(20);

b.setWidth(30);

Logger.log(b.getSize());

When I create these kind of functions, I always like to make them chainable, so when you use any of my libraries, and you like chaining, look out for opportunities to do this.

On the other hand, too much chaining can lead to unreadable code (remember that others may have to read it too), and a lack of proper error handling. That said, chaining can give a remarkably concise way of expressing a complex set of actions - and I just like the way it all fits together.