Wednesday, September 25, 2019

Chaining JavaScript methods

JavaScript allows you to invoke multiple methods on an object in a single expression. This is called chaining and is accomplished by stringing the method calls together with dots between them, like so:
  1. object.method1().method2().method3();
When building a chain the object is named only once and then multiple methods are called on it. For this to work, your methods must return the object that they operate on. Each method works on the object and when it is done it returns it to the next call. This gives rise to a chain of method calls in a single expression.
Here is a real-world example of a banking account in which the account number, the balance, and a line of credit are set:
  1. account.number("012477630").setBalance(10971).applyCredit(200);
Chaining in JavaScript can improve performance as well as readability. The jQuery library uses chaining extensively; here is an example of how to chain jQuery selector methods:
  1. $("#myDiv").removeClass("off").addClass("on").css("background": "red");
This coding style cuts down significantly on jQuery's selector use, which is useful because usually this is where jQuery spends most of its time. Let's look at another jQuery example. Consider this piece of HTML code:
<ul class="horizontal_list">
    <li class="one">Home<li>
    <li class="two">About Us</li>
    <li class="three">Contact Us</li>
</ul>
We now use jQuery to make two background color changes; the Home menu item red and Contact Us light blue. Here is the jQuery chained expression that will accomplish this:
  1. $("ul.horizontal_list")
  2. .find(".one").css("background-color", "red").end()
  3. .find(".three").css("background-color", "lightblue");
Run  Clear
  • Home
  • About Us
  • Contact Us
First, the jQuery selector returns the entire ul element with class="horizontal_list". Next the find() method locates the item with class "one" within the ul element and the subsequent css() method sets its background color to red. The end() method tells the object to return to its initial state i.e. go back to the ul before the second find() is invoked. 
The second find() then searches for the item with class "three" inside the ul element and the next css() method turns its background to light blue. The outcome is that the Home and Contact Us items of the horizontal_list have colored backgrounds.
These examples clearly show the benefits of chaining. First, there is no need to store the return value of a previous method in a temporary variable. Second, it lets you perform multiple complex operations in a single concise, easy-to-read expression. And third, performance is better. This technique can be very beneficial in your own JavaScript projects.
A disadvantage of chaining is that it may be difficult to debug; in case of an error you have no idea which method in the chain failed.

No comments:

Post a Comment