Wednesday, June 5, 2013

JavaScript Learning# 7 - Static variables and methods

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:
1static int count = 0;void f() { 
2
3 count++;
5}
6 
7new 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).
1function f() {
2  f.count = ++f.count || 1 // f.count is undefined at first
3 
4  alert("Call No " + f.count)
5}
6 
7f(); // Call No 1
8f(); // 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.
1function 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 Smile

Static methods

Static methods, just like variables, are attached to functions. They are used mostly for objects:
01function Animal(name) {
02  arguments.callee.count = ++arguments.callee.count || 1
03 
04  this.name = name
05}
06 
07Animal.showCount = function() {
08  alert( Animal.count )
09}
10 
11var mouse = new Animal("Mouse")
12var elephant = new Animal("elephant")
13 
14Animal.showCount()  // 2




No comments:

Post a Comment