What is Method Chaining in Javascript?
What is method chaining? Well, from a high level, think of it as a chain of method calls. More specifically, if you have some methods that return objects when invoked, then what you can do is use an object returned from one method invocation to invoke yet another method. This process of can then be continued indefinitely – where one method call is used to make another method call – forming a “chain” of method calls.
This chain is just a single expression. It’s easy enough to break this chain down and make each of the calls into separate expressions, but then it would obviously not be method chaining anymore.
Example of Method Chaining Pattern in Javascript
Actually, the JQuery library makes extensive use of method chaining. Let’s go through an example so that it’s clear to you how method chaining works. Here is an example of what method chaining in would look like using JQuery:
$("#h1").text("Change text").css("color", "red");;
In the example above, the h1 element will have it’s text changed to “Change text”, and then the color of the text will also be changed to red.
Method Chaining Return Value
If you create a Javascript method that does not have a return value, then you might want to have that method return this. If this is returned from a method then you can perform method chaining on the methods that you define. Remember that method chaining will only work if the return value of the methods being chained is an actual object.