Skip to content

Function chaining in JavaScript | Pattern

  • by

JavaScript Function chaining is nothing but grouping functions in one single line using dot notation. Function chaining or Method Chaining is a mechanism of calling a method on another method of the same object.

Function chaining in JavaScript

Simple example code using function chaining with regular objects. The functions such as add() and subtract() are returned and made function chaining possible there by displaying 3 as the output.

this keyword in JavaScript refers to the current object in which it is called. Thus, when a method returns this, it simply returns an instance of the object in which it is returned.

<!DOCTYPE html>
<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(){
       console.log("Function chaining",this.i);
     }
   }

   var x = new obj();
   x.add(100).subtract(50).print();

 </script>

</body>
</html> 

Output:

Function chaining in JavaScript

More Example

<script>
    function Land() {
      this.area = '';
      this.status = 'for Sale';
    }

    Land.prototype.open = function() {
      this.status = 'Open for Sale';
      return this;
    }

    Land.prototype.close = function() {
      this.status = 'Not for Sale';
      return this;
    }

    Land.prototype.setParams = function(area) {
      this.area = area;
      return this;
    }

    Land.prototype.doorStatus = function() {
      console.log('The',this.area,'Land is',this.status);
      return this;
    }

    var land = new Land();
    land.setParams("500 sq ft").close().doorStatus();

</script>

Output: The 500 sq ft Land is Not for Sale

var Obj = {
  result: 0,
  addNumber: function(a, b) {
    this.result = a + b; 
    return this;
  },

  multiplyNumber: function(a) {
    this.result = this.result * a;
    return this;
  } 
};

Obj.addNumber(10, 20).multiplyNumber(10)
console.log(Obj.result)

Output: 300

Do comment if you have any doubts or suggestions on this JS concept.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *