Fluent Interfaces in JavaScript
Fluent interfaces provide a set of chained methods to manipulate a value in an object. It can help turn complex operations involving many steps into a relatively straightforward set of operations while providing a lot of flexibility. Many libraries like jQuery, Mongo DB and so on use this. To demonstrate, here is a simple string manipulator:
function Formatter(message) { const self = this; self.value = message; self.lastAction = function() {}; const wrap = function(callback) { return function() { const argsAsArray = [].slice.call(arguments); callback.apply(self, argsAsArray); self.lastAction = callback.bind(callback, argsAsArray); return self; } } self.prefix = wrap(function(prefix) { self.value = prefix + self.value; }); self.suffix = wrap(function(suffix) { self.value += suffix; }); this.times = wrap(function(times) { // -1 since the action has already been done once for (let i = 0; i < times - 1; i += 1) { self.lastAction(); } }); }; const value = new Formatter('My exciting sentence') .suffix('!') .times(5) .prefix('[') .suffix(']') .value console.log(value); // [My exciting sentence!!!!!]
It is important to use a wrapper function, so that further functions do not accidentally lack self returns due to copy and pasting errors.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2017/fluentInterface.js














