Saturday, July 14, 2007

static variable of Javascript

<script type="text/javascript" charset="utf-8">
function doc (argument) {
document.write("<br />\n");

// Define a static variable to hold the running static_var over all calls
// Can't claim static variable with key "var", this is function Object's properties
function doSome (a) {
doSome.static_var ++;
return a + doSome.static_var;
doc(typeof doSome); //function Object
doSome.static_var = 0; // var doSome.static_var = 0 will error.
doc(doSome(1)); //2
doc(doSome(1)); //3
doc(doSome(1)); //4
doSome.static_var = 0;
doc(doSome(1)); //2
for (i in doSome)

Class Properties
In addition to instance properties and properties of prototypes, JavaScript allows you to define class properties (also known as static properties), properties of the type rather than of a particular object instance. An example of a class property is Number.MAX_VALUE. This property is a type-wide constant, and therefore is more logically located in the class (constructor) rather than individual Number objects. But how are class properties implemented?
Because constructors are functions and functions are objects, you can add properties to constructors. Class properties are added this way. Though technically doing so adds an instance property to a type’s constructor, we’ll still call it a class variable. Continuing our example,

doSome.static_var = 0;

defines a class property of the doSome object by adding an instance variable to the constructor. It is important to remember that static properties exist in only one place, as members of constructors. They are therefore accessed through the constructor rather than an instance of the object.
As previously explained, static properties typically hold data or code that does not depend on the contents of any particular instance. The toLowerCase() method of the String object could not be a static method because the string it returns depends on the object on which it was invoked. On the other hand, the PI property of the Math object (Math.PI) and the parse() method of the String object (String.parse()) are perfect candidates, because they do not depend on the value of any particular instance. You can see from the way they are accessed that they are, in fact, static properties. The isMetallic property we just defined is accessed similarly, as doSome.static_var.

No comments :