javascript interactive

JavaScript Interactive — a console crash course


5.5 Chained Method Calling

Warning: Your browser may be outdated or unsupported.

The JavaScript console is known to display some of the examples incorrectly in Internet Explorer 8 or older.
>>>
function A(value) {
    this.value = value;
}

  
>>>
A.prototype.val = function () {
    return this.value;
};

  
Popularized by the jQuery library, chained method calls is now commonly used with objects. The simple A object is here used to illustrate this concept.
>>>
A.prototype.add = function (term) {
    this.value += term;
    return this;
};

  
The A.prototype.add() method modifies the value. But it also makes sure to return this, i.e. the object instance itself.
>>>
A.prototype.mul = function (term) {
    this.value *= term;
    return this;
};

  
Similarly, the A.prototype.mul() also returns this. Naturally, returning this only makes sense for mutator methods or methods that wouldn't return some other value.
>>>
new A(1).add(2).mul(3).val()
9
As the methods return the object instance, it is possible to chain several method calls together. This can make the code more compact, as intermediary variable declarations are avoided.
>>>
A.prototype.log = function () {
    print('this.value = ' + this.value);
    return this;
};

  
Method chaining can make debugging harder, since a single line of code (or an expression) now contains so many calls. To handle this, a log() method is sometimes introduced to inspect intermediary results.
>>>
new A(1).log().add(2).log().mul(3).log().val()
9
The original chain becomes less readable, but changes to the value are now easy to trace.
>>>

Index 1 2 3 4 5 6 7 8