static variables in javascript
In javascript functions and objects work in the same manner. Functions are also objects.
so a function can have a member variable like in objects.
A member variable will retain its value between function calls.
So this aspect is used for having a static variable in javascript.
Actually there is no option like static variables in javascript. so here the member variable server as a static variable in javascript.
here is one simple script which uses a static variable to maintain a counter
<script> function addmore() { if(!addmore.counter)addmore.counter = 0; addmore.counter++; alert(addmore.counter) } addmore(); addmore(); </script> |
or here is another version
<script> function addmore() { if(!this.counter)this.counter = 0; this.counter++; alert(this.counter) } addmore(); addmore(); </script> |
i have used this for multiple file uploads where there will be an addmore button and a variable to maintain the count of number of uploads to display and once this.counter is greater than 10 then i alert a message that uploads cannot be more than 10.
some people had an idea that why done we use like the following instead of using it like a member function
<script> var counter=0 function addmore() { counter++; alert(counter); } addmore(); addmore(); </script> |
my answer is not to mess up the code with too many declarations which uses the word var…
after a long time we would wonder which variable is for which function
and if the variable is with respect to the context of the process then that will a good practice of maintaing standards and more meaningful.
if you would like to suggest an alternate please comment on this because i would like to know more if there is anything beyond my scope on this.
July 12th, 2010 at 5:33 pm
Nice solution. Well done!!!
February 26th, 2012 at 11:07 pm
thanks dear,
i need a counter u gave very simple code for the same.
September 3rd, 2013 at 12:04 pm
finally i got static variable in javascript,clear solution
thanks dude
October 10th, 2013 at 12:28 am
You can use a closure
var addMore = (function() {
var counter = 0;
return function() {
counter++;
console.log(counter);
}
})();
for (var i = 0; i < 10; i++) {
addMore();
}
October 10th, 2013 at 12:35 am
I meant to say “you can *also* use a closure”, your solution is perfect for the need.