How to make chainable function in JavaScript?

daGrevis picture daGrevis · Oct 11, 2011 · Viewed 16.7k times · Source

Lets imagine function like this:

function foo(x) {
    x += '+';
    return x;
}

Usage of it would be like:

var x, y;
x = 'Notepad';
y = foo(x);
console.log(y); // Prints 'Notepad+'.

I'm looking for a way to create function that's chainable with other functions.

Imagine usage:

var x, y;
x = 'Notepad';
y = x.foo().foo().toUpperCase(); // Prints 'NOTEPAD++'.
console.log(y);

How would I do this?

Answer

Alex Turpin picture Alex Turpin · Oct 11, 2011

Sure, the trick is to return the object once you're done modifying it:

String.prototype.foo = function() {
    return this + "+";
}

var str = "Notepad";
console.log(str.foo().foo().toUpperCase());

http://jsfiddle.net/Xeon06/vyFek/

To make the method available on String, I'm modifying it's prototype. Be careful not to do this on Object though, as it can cause problems when enumerating over their properties.