Javascript method chaining example

Written by stevey on November 10th, 2014

Javascript method chaining is basically a chain of method calls that instead of call multiple times, just get called once and “chained” to one single object instance – the singleton pattern here. Below are some working samples I created after reading a good reference at http://coursesweb.net/javascript/chain-methods-javascript-object; to try it out, just copy the codes below and paste it to a notepad and then render in any browser.

<html>
<body>
<div id="d1">
<h3>Method chaining example</h3>

<a href="javascript:getArea();">Get Area</a>
<br />
<a href="javascript:getPerimeter();">Get Perimeter</a>
</div>

</body>
</html>

<script type="text/javascript">
var rec=new Rectangule();

function getArea()
{
//alert(rec.Area(3,4)); //this is without chaining
alert(rec.SetParam(3,4).Area()); //chaining

}

function getPerimeter()
{

//alert(rec.Perimeter(3,4));
//method chaining
alert(rec.SetParam(3,4).Perimeter());

}
function Rectangule()
{
var a=0,b=0;

this.SetParam=function(a1,b1){
a=a1;b=b1;
return this; //this is what makes chaining possible.
}

this.Area=function(){
return a*b;

}

this.Perimeter=function(){
return 2*(a+b);

}

}

</script>

 

Leave a Comment