Static JavaScript attributes It is a fun thing. It is different from Java and so on. Language
In Java, for example, a person class has a static attribute, and all objects have the same address space, that is:
Changing the static property of an object also changes the value of this property of another object.
In JavaScript, the situation is different, as shown below: Code :
Function person (name, age ){
This. Name = Name; // attribute
This. Age = age; // attributes // Method
This. Show = function (){
Alert ("name:" + this. Name + "; age:" + this. Age );
}
}
Person. Prototype. totalcount = 8; // static attribute
Person. showtotalcount = function () {// static method
Alert (person. Prototype. totalcount );
}
VaR me = new person ("freish", 23 );
Me. totalcount ++; // use the object to change the value of totalcount alert (Me. totalcount); // here is 9, no doubt
Person. showtotalcount (); // However, the static attribute value of the class has not changed! Still 8
The experiment is summarized as follows:
Static variables of A Class belong to the class itself, not the object, but can be accessed through the object (get the value of the static attribute of the class ). If you assign values (including ++ and --) to a class static attribute through an object, a unique variable is created for the object, the operation result will be saved in the newly created object variable. After the value is assigned, you cannot access the static attributes of the class through this object, but you can only access the newly created variable!
Analyze me. totalcount ++ in the above example;
Me. totalcount ++ is roughly equivalent to me. totalcount = me. totalcount + 1;
On the Right of the equal sign, "me. totalcount" takes the value of the class's static attribute "totalcount", because the totalcount value of the object "me" has not been assigned yet;
Add 1 and assign a value. In this case, create a totalcount variable for the object me and give the result to the new variable without changing the value of totalcount.
In this way, the newly created variable will be accessed through me. totalcount!