Lets imagine function like this:
JavaScript
x
5
1
function foo(x) {
2
x += '+';
3
return x;
4
}
5
Usage of it would be like:
JavaScript
1
5
1
var x, y;
2
x = 'Notepad';
3
y = foo(x);
4
console.log(y); // Prints 'Notepad+'.
5
I’m looking for a way to create function that’s chainable with other functions.
Imagine usage:
JavaScript
1
5
1
var x, y;
2
x = 'Notepad';
3
y = x.foo().foo().toUpperCase(); // Prints 'NOTEPAD++'.
4
console.log(y);
5
How would I do this?
Advertisement
Answer
Sure, the trick is to return the object once you’re done modifying it:
JavaScript
1
7
1
String.prototype.foo = function() {
2
return this + "+";
3
}
4
5
var str = "Notepad";
6
console.log(str.foo().foo().toUpperCase());
7
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.