Chaining - Fluent Interfaces In JavaScript
Chaining - Fluent Interfaces In JavaScript
Written by Ian Elliot   
Friday, 23 February 2018
Article Index
Chaining - Fluent Interfaces In JavaScript
Getting Complicated

One of jQuery's attractive features is the way that you can build up chains of commands that look almost like the way you would use a language. This is more generally called a "Fluent Interface" and it isn't difficult to implement in JavaScript.

JavaScript Jems
Patterns & Practice



  1. JavaScript Patterns 
    Why JavaScript is a Jem
  2. Objects with Values in JavaScript
    JavaScript Objects With Value - valueOf and toString
  3. A JavaScript TimeInterval object
  4. Date Hacks - Doing JavaScript Date Calculations
  5. Private Functions In JavaScript
  6. Chaining - Fluent Interfaces In JavaScript
  7. Active Logic, Truthy and Falsey
  8. The Confusing Comma In JavaScript
  9. Self Modifying Code
  10. Lambda expressions
  11. Master JavaScript Regular Expressions
  12. The Function Approach To Programming

The idea of a fluent interface was first coined by Eric Evans and Martin Fowler to express the idea of an object- oriented API. The technique uses method chaining, but if you want to call it a fluent interface it also has to have the characteristics of a domain specific language. Put simply, the way that the methods chain together has to express natural sets of operations. Ideally the chains of methods should read as if you were writing a tiny program with verbs and modifiers. 

First let's take a look at the mechanism of chaining.

In what follows don't worry to much about why you would want to do things. Concentrate instead on how they work.

The reasons and advantages of chaining and fluent interfaces will become clear later.

General Chaining

Chaining is where you call one function after another. For example:

 and so on...

It is usual, but not necessary, for the first function to be a method belonging to a particular object.

 and so on...

The object version of the chaining is the common idiom in other languages where functions aren't first class objects. In JavaScript, however, functions are first class objects and this makes the first form of chaining perfectly reasonable.

When you first see something like this, you can't help but wonder why it all works. Indeed, it doesn't work unless you arrange for the functions to fit together.

The principle of chaining is that each function has to return an object, which supports the next function in the chain as a method.

This is all there is to function chaining - it's simple but it is easy to become confused in real cases.

Take for example the chain:


For this to work function1 has to return an object which has function2 as a method. For simplicity, suppose obj2 has function2 as a method and obj3 has function3 as a method. First we need to define function1:

function1 = function(){
                        alert("function 1");
                        return obj2;

As promised, this returns obj2 which is defined as:

var obj2 = {

            function2: function () {
                        alert("function 2");
                        return  obj3;

which, again as promised, returns obj3 which is defined as:

var obj3 = {

            function3: function () {
                        alert("function 3");
                        return obj3;

With these definitions you can now write:


and when you run the program you will see three alert boxes announcing function1, function2 and function3 in turn.

Of course, in practice the functions could have parameters and the objects could be generated by constructor functions requiring that we use new to create a new instance of each object to return.

Notice that it is the object returned by each function that gives the next function in the chain its context.

That is, you can determine exactly what function is called by the object you return. That is not only is this set to the object you have returned but the function that is used depends on the object you return.

For example, if the function was a search operation, then the display function called next could be automatically varied according to the type of object returned by the search. That is you call .display but the function you get depends on the object returned. This is a sort of natural polymorphism that all dynamically typed languages have.

Also notice that if you want to define function1 as a method of obj1 then this works, but now you have to start the chain with obj1:


This is all there is to function chaining and it all depends on each function returning an object which has the next function among its methods.

However, this isn't the most common way that function chaining is used.

Singleton Chaining

Before we get on to more complicated examples, let's examine another simple case - singleton chaining.

A singleton is a JavaScript object that isn't created by a constructor - it is an object literal.

In this case what we want to do is allow each function to be defined as a method of the same object - obj say. To allow chaining we have to arrange for each method to return an object that each subsequent function is defined on and in this case it is just obj. It really is this simple.

So let's define our object with three methods:

var obj = {
            function1: function () {
                return obj;
            function2: function () {
                return obj;
            function3: function () {
                return obj;

Notice that each function returns a reference to obj and this is what allows the next function call in the chain to work. With this definition you can write:


and you will see the three alert boxes indicating that each function is called in turn.

Notice that this all depends on the variable obj not being reassigned between function calls. If you want to protect against this you need to create a private variable using closure that cannot be changed that the functions can return or you can use a const if you are using ES2015.

Instance Chaining

Singletons can be very useful, but often we want to be able to create as many instances of an object as desired and in this case we have to move on to look at instance chaining.

This is very similar to the singleton case, but now we have to create a constructor that will produce an instance of the object.

var objConstruct = function(){
            this.function1= function () {
                return this;
            this.function2=function () {
                return this;
            this.function3= function () {
                return this;

Notice that we have defined three methods for the object we are constructing, but also notice the use of "this" to reference the object being constructed.

What should each of the functions return to ensure that the next function can be called?

In this case each function has to return "this" because when the function is called "this" references the instance that the function is a method of.

Now we can write:

var obj = new objConstruct();

and again we see the alert boxes announce that each function is called in turn.

If you can't see the difference between this and the singleton example, remember that we can now create as many instances of the object as we like. Also notice that because each function returns "this" as the object for the next function all of the function in the chain are called in the context of the same instance of the object.


Last Updated ( Friday, 23 February 2018 )

RSS feed of all content
I Programmer - full contents
Copyright © 2018 All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.