Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
39
rated 0 times [  43] [ 4]  / answers: 1 / hits: 19708  / 13 Years ago, tue, october 11, 2011, 12:00:00

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?


More From » function

 Answers
230

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.


[#89675] Monday, October 10, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
soniap

Total Points: 626
Total Questions: 119
Total Answers: 110

Location: Palestine
Member since Tue, Jul 20, 2021
3 Years ago
;