Static Variables in JavaScript

How do you declare a static variable in a JavaScript function?
Not with the word “static“.
In JavaScript “function” is a variable type similar to “object“.
The difference is that the reference to a function inside itself is not this but arguments.callee.
An example of using arguments.callee is the following function that returns itself:

function func(){
    return arguments.callee;
}

Adding Static Variables

You can add arguments to arguments.callee. To initialize it the first time, check first if it is not defined. For example:

if (typeof(arguments.callee.myStaticVar)!="undefined")
    arguments.callee.myStaticVar=0;

Following is an example function in [rhino(http://rhino.org) JavaScript(run from the command line):

    function _example(){
        var thisFunction = arguments.callee;
        if (!thisFunction.static){
            thisFunction.static=0;
        }
        ++thisFunction.static;
        print("This function has been called: " + thisFunction.static + " times");
    };

In this example, you can change the static variable’s value without calling the function using _example.static = "some value";.

To prevent this, encapsulate your function using a function called once, for example:

(function(){
    function _example(){
        var thisFunction = arguments.callee;
        if (!thisFunction.static){
            thisFunction.static=0;
        }
        ++thisFunction.static;
        print("This function has been called: " + thisFunction.static + " times");
    };

    example=function(){
        _example();
    }
})();

Now, each time example() is called, it will increment the variablestatic, but the variable cannot be incremented without calling example because _example is private.

Written with StackEdit.

Advertisement