Static variables in JavascriptStatic variables are variables, typically used in functions, that maintain their value between function calls. Javascript does not support static variables per se; their is no static keyword in the language. However in javascript all functions are also objects and we can use this fact to simulate static variables. All we have to do is create a variable that is a member of the function, and since it‘s now part of an object, the value will be retained between calls. While there aren‘t truly static in the strictest sense of the word, they maintain their value between functions calls, and that usually serves the purpose.
As an example, consider a completely lame, but very instructive, function that keeps track of the number of times that it has been called. Here‘s how it might look: function countMyself() { // Check to see if the counter has been initialized if ( typeof countMyself.counter == ‘undefined‘ ) { // It has not... perform the initilization countMyself.counter = 0; } // Do something stupid to indicate the value alert(++countMyself.counter); } function countMyself() { if(this.a == null){ alert(++this.a);
Each time that the countMyself function gets called from the page, the value is shown increasing by one. Using this trick, you can easily simulate static variables in Javascript. |
|