Static variables and methods
A function is an object. That provides us with a nifty way to create static variables or, in other words, the variables which persist along multiple calls.
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() { |
2 |
3 | count++; |
5 | } |
6 |
7 | new f(); new f(); new f(); // 1 2 3 |
In JavaScript, there is no term or keyword static, but we can put such data directly into function object (like in any other object).
1 | function f() { |
2 | f.count = ++f.count || 1 // f.count is undefined at first |
3 |
4 | alert( "Call No " + f.count) |
5 | } |
6 |
7 | f(); // Call No 1 |
8 | f(); // Call No 2 |
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
.1 | function f() { |
2 | arguments.callee.count = ++arguments.callee.count || 1 |
3 |
4 | alert( "Called " + arguments.callee.count + " times" ) |
5 | } |
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 |
03 |
04 | this .name = name |
05 | } |
06 |
07 | Animal.showCount = function () { |
08 | alert( Animal.count ) |
09 | } |
10 |
11 | var mouse = new Animal( "Mouse" ) |
12 | var elephant = new Animal( "elephant" ) |
13 |
14 | Animal.showCount() // 2 |
source: http://javascript.info/
No comments:
Post a Comment