For example, we want a variable which counts function calls.
Static variables
There are languages which allow to put a static keyword before a variable, and then such variable is not cleared in next calls.
Example of a static variable in Java language:
1 | static int count = 0; void f() { |
7 | new f(); new f(); new f(); |
In JavaScript, there is no term or keyword static, but we can put such data directly into function object (like in any other object).
2 | f.count = ++f.count || 1 |
4 | alert( "Call No " + f.count) |
Of course, a global variable can keep the counter, but static variables lead to a better architecture.
We could make the code more universal by replacing f
with arguments.callee
.
2 | arguments.callee.count = ++arguments.callee.count || 1 |
4 | alert( "Called " + arguments.callee.count + " times" ) |
Now you can safely rename the function if needed
Static methods
Static methods, just like variables, are attached to functions. They are used mostly for objects:
01 | function Animal(name) { |
02 | arguments.callee.count = ++arguments.callee.count || 1 |
07 | Animal.showCount = function () { |
11 | var mouse = new Animal( "Mouse" ) |
12 | var elephant = new Animal( "elephant" ) |