JavaScript Cascade function

In a cascade, we can call many methods on the same object in sequence in a single statement.
The trick is that the method itself should only return this. That way, each time you chain these methods together, the object itself is the base of the call. This is how JQuery works.

Lets try this example,

var Calc = function(){    
  this.result=0;

  this.add = function(){      
    for(var x=0; x<arguments.length; x++){
      this.result += arguments[x];
    }     
    return this;
  };

  this.sub = function(){
    for(var x=0; x<arguments.length; x++){
      this.result -= arguments[x];
    }         
    return this;
  };

  this.mult = function(){
    if(this.result==0)this.result = 1;
    for(var x=0; x<arguments.length; x++){
      this.result *= arguments[x];
    }         
    return this;
  };

  this.div = function(){
    if(this.result==0) return this;
    for(var x=0; x<arguments.length; x++){
      this.result /= arguments[x];
    }         
    return this;
  };

  this.eq = function(){
    return this.result
  };

}

var cal1 = new Calc();

cal1.add(3).sub(1).add(2) // Here result = 4;
Advertisements

One thought on “JavaScript Cascade function

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s