Pages

Saturday, November 12, 2011

Retain value between function calls without using global variables in JavaScript using callee



                Normally when we want to retain a value we use a global variable which is defined outside the scope of the function we are calling. But we can actually retain a value without using global variables but by using built in variables passed to the function. When a function is called two built in variables are made available to the function. One of them is the arguments variable. This variable contains a property named callee which contains a reference to the function itself.
                Since we can get a reference to the function we can use a property for that function to store the required value. See the example.

function deposit(amount){

var funct=arguments.callee;

 if(!funct.balance)
{
funct.balance=0;
}
funct.balance+=amount;

 return funct.balance;
}


When the function is called for the first time there is no property named balance for the function. Therefore we have to check it an initialize the property. Afterwards, we each time the function get called we can extract the stored value and modify it finally return the value. I tried and failed to develop a self-modifying function to avoid check each time and only check once for the existence of the property. You may give it a try!

Just  copy and paste this to firebug console and add these to check.

deposit(10);  //this would return 10