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
deposit(20); // this would return 30
You may also like to read
Change the Context using call() and apply() in JavaScriptRedefine function within function to avoid unnecessary if else blocks in JavaScriptWrapping a block of String within a particular element with HTML elements in JQuery using special key words to identify the blockhttp://jayaprabath.blogspot.com/2011/06/restrict-users-to-enter-numeric-values.html
You may also like to read
Change the Context using call() and apply() in JavaScriptRedefine function within function to avoid unnecessary if else blocks in JavaScriptWrapping a block of String within a particular element with HTML elements in JQuery using special key words to identify the blockhttp://jayaprabath.blogspot.com/2011/06/restrict-users-to-enter-numeric-values.html