What is function chaining in JavaScript?


Function chaining

Function chaining is nothing but grouping functions in one single line using dot notation. This type of chaining makes the code very concise and also improves the performance.Here we are going to learn function chaining using regular objects.

a) Without function chaining 

In the following example an object 'obj' is created and in that object a public property called 'i' is created using keyword 'this' and initially assigned a value 0. later on user defined functions called add(), subtract() and print() are created inside the same object 'obj'. Now, the object "obj" will acts like a class(it's properties can be shared by other objects).

Now one more object called 'x'(user defined) is created using keyword 'new' and made accessible to use the properties of the object "obj". Since, the functions declared inside the "obj" such as add(), subtract() and print() are not returned, function chaining is not possible and undefined is displayed as the output whereas individually(unchained) those functions will execute the output as 3(user provided '5-2').

Example

Live Demo

<html>
<body>
<script>
   var obj = function(){
      this.i = 0;
      this.add = function(i){
         this.i += i;
       };
       this.subtract = function(i){
          this.i -= i;
       };
       this.print = function(){
          document.write(this.i);
          document.write("</br>");
          document.write(x.add(3));  // returns undefined
       }
   }
   var x = new obj();
   x.add(5);
   x.subtract(2);
   x.print(); // 5-2 = 3 so prints 3.
   x.add(5).subtract(2).print();  //  function chaining is not possible so undefined
</script>
</body>
</html>

Output

3
undefined

b) With function chaining

In the following example, considering the above example scenario, using user defined "return this" statement, the functions such as add() and subtract() are returned and made function chaining possible there by displaying 3 as the output.

Example

Live Demo

<html>
<body>
<script>
   var obj = function(){
      this.i = 0;
      this.add = function(i){
         this.i += i;
         return this;
      };
      this.subtract = function(i){
         this.i -= i;
         return this;
      };
      this.print = function(){
         document.write(this.i);
      }
   }
   var x = new obj();
   x.add(5).subtract(2).print();
</script>
</body>
</html>

Output

3
raja
Published on 18-Jun-2019 17:29:24
Advertisements