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:


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")

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

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

View original post 119 more words