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?
There is no formal usage syntax when chaining. The convention is to either chain the calls on a single line if short or to chain on the new line indented one tab from the referenced object with the dot on the new line. Use of the semicolon is optional but does help by clearly denoting the end of the chain.
Adjective. chainable (not comparable) Capable of being chained or connected together.
Function chaining is nothing but grouping functions in one single line using dot notation. This type of chaining makes the code very concise and also improves the performance.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With