How To Create (optionally) Chainable Functions Like In Lodash?
A common, and very readable, pattern found in Lodash is 'chaining'. With chaining, the result of the previous function call is passed in as the first argument of the next. Such as
Solution 1:
One example on how to do it
functionfoo(arr) {
if (!(thisinstanceof foo)) {
returnnewfoo(arr);
}
this.arr = arr;
returnthis;
}
foo.prototype.add = function(p) {
this.arr.push(p);
returnthis;
}
foo.prototype.print = function() {
console.log(this.arr);
returnthis;
}
foo([1, 2]).add(3).print();
Say you want to do this as well
foo.add(3).print();
You need to create a method on foo
(not the prototype)
foo.add = function(p) {
return foo([p]);
}
foo.add(3).print() // [3]
Solution 2:
It's called method chaining. Here's two articles on it. The basic gist of it is that you return the current object at the end of the function.
http://schier.co/blog/2013/11/14/method-chaining-in-javascript.html
Post a Comment for "How To Create (optionally) Chainable Functions Like In Lodash?"