Let's assume I have three functions one(), two(), three(), etc. I want these function to support chaining.
Example :
one().two().three();
or
three().two().one();
Something similar to calling many APIs in JavaScript:
fetch().then().then()
In most languages, chaining is based on whatever is returned. In other words, the return from the method is passed to the chained method as this. It can be the previous method's this, or anything else that you might return.
For instance, with fetch:
fetch returns a new Promise object. That Promise object has a method called then() attached to it.
Use classes.
class Console {
log(...args) {
console.log(...args);
return this;
}
warn(...args) {
console.warn(...args);
return this;
}
error(...args) {
console.error(...args);
return this;
}
}
const con = new Console();
con
.log("Hello")
.warn("You really shouldn't do that")
.error("Danger!");
Or if you're stuck with ES5:
var con = {
log: function () {
console.log.apply(console, arguments);
return this;
},
warn: function () {
console.warn.apply(console, arguments);
return this;
},
error: function () {
console.error.apply(console, arguments);
return this;
}
};
con
.log("Hello")
.warn("You really shouldn't do that")
.error("Danger!");
Ibrahim Tanyalcin
{intrst:"Scnc&Art",msc:"admin@MutaFrame",strive:"Experiment&Learn",loves:"ES5",hates:"bandwagon",lang:"Javascript",twttr:"@ibrhmTanyalcin"}
To chain you need to return an object that either has the next method as own property or somewhere in its prototype chain. I will make a simple calculator for you:
function calculator(){ this.ledger = []; this.timeout = 0; this.callback = function(x){console.log(x)}; } calculator.prototype.add = function(v){ v = +v; v = v !== v ? 0 : v; clearTimeout(this.timeout); this.timeout = setTimeout((function(){this.callback(this.ledger.reduce(function(ac,d){return ac +d})); this.ledger = [];}).bind(this),0); this.ledger.push(v); return this; } var x = new calculator; x.add(1).add().add(0); //1 x.add(5).add(-2).add(3); //6