Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make chainable function in JavaScript?

Tags:

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?

like image 938
daGrevis Avatar asked Oct 11 '11 17:10

daGrevis


People also ask

How do you chain objects in JavaScript?

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.

What is Chainable?

Adjective. chainable (not comparable) Capable of being chained or connected together.

What is function chaining in JavaScript?

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.


1 Answers

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.

like image 52
Alex Turpin Avatar answered Sep 26 '22 21:09

Alex Turpin