JavaScript: method chaining

JavaScript allows us to chain methods by simply making methods return the this keyword, that is, themselves. So you can have method1().method2().methodN() and so on, all members of the same chain. This turns out to be very useful when you want to concatenate some subroutines and, most of all, when you want to keep your code tidy and organized by avoiding functions and methods that make too much. The basic structure is as follows:

var Class = {
  
  method1: function() {
  
    //...
    
    return this;
  
  },
  
  method2: function() {
  
    //...
  
    return this;
  
  },
  
  methodN: function() {

    // end of the chain

  }
};

You can use this technique as follows:

Class.method1().method2().methodN();

A practical example:

var Class = {

  element: document.getElementById('test'),
  
  grow: function() {
  
  
    this.element.style.width = '180px';
    this.element.style.height = '180px';
    
    
    return this;
  
  
  },
  
  move: function() {
  
  
    var counter = 0;
    
    var interval = setInterval(function() {
    
    
      counter += 1;
      
      Class.element.style.left = counter + 'px';
      
      if(counter == 100) {
      
      
        clearInterval(interval);
        
        var interval2 = setInterval(function() {
        
        
          counter -= 1;
          
          Class.element.style.left = counter + 'px';
          
          if(counter == 0) {
          
            clearInterval(interval2);
            
            Class.element.style.width = '150px';
            Class.element.style.height = '150px';
          
          
          }
        
        
        
        }, 25);      
      
      }
    
    
    
    }, 25);
  
  
  },
  
  run: function() {
  
    var trigger = document.getElementById('run');
    
    run.onclick = function() {
    
      Class.grow().move();
      
      return false;
    
    
    
    };
  
  
  
  }


};


Class.run();

};

You can see the demo below.

Demo

Live demo

Leave a Reply

Note: Only a member of this blog may post a comment.