Static Variables in JavaScript


PHP & More

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:

functionfunc(){returnarguments.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=;

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=;
        }
        ++thisFunction.static;
        print("This function has been called: " + thisFunction.static

View original post 119 more words