Method chaining is a way to return an object from a method call that allows for further methods to be called. It’s easier to see than to describe.
Instead of this:
You could do this:
We get code with fewer variables that’s easier to read.
It does make your code more susceptible to null reference errors but, if you’re happy to deal with that, then this can be a good way to make your code that little bit more intuitive to use.
At the moment, our public methods don’t return anything. To get method chaining to work, we need to update these methods to return the next object that we want to call. In this case, we’ll be returning a reference to the current object.
What’s this?
In JavaScript this always refers to the “owner” of the function we’re executing, or rather, to the object that a function is a method of.
— quirksmode.org
In our library, we’re defining the public functions as objects within the main (anonymous) function. At that point, this references the container function.
So, all we need to do is make sure that our functions return this and we can chain away as much as we want.