JavaScript static variables and instance variables
Blog Category:
Strictly speaking, JS inside there is no static and private concept, all member properties are public, the following is only reference Oo language, in some way to achieve similar concepts.
One. static variables
1. private static variables
All instances are shared. Because it is a private variable, it cannot be accessed directly by the function name. implemented by closures.
According to the scope principle of the closure, it can only be accessed within the closure package. Therefore, it is not possible to access this static variable anywhere in the class. Only constructors or methods of the class (the prototype method) can be accessed within the closure.
JS Code
- (function () {
- var privatestatic = "Privatestatic";
- Func = function () {
- this.setprivatestatic = function (value) {
- Privatestatic = value;
- }
- this.getprivatestatic = function () {
- return privatestatic;
- }
- }
- })();
- var func1 = new Func ();
- var func2 = new Func ();
- Console.log (Func1.getprivatestatic ()); //Privatestatic
- Console.log (Func2.getprivatestatic ()); //Privatestatic
- Console.log (func1.setprivatestatic (' changed '));
- Console.log (Func2.getprivatestatic ()); //changed
2. public static variables
This is relatively straightforward and directly defines the properties of the function.
Backbone's extend function has two parameters, the first argument is an instance variable, and the second argument is a static variable. This is how the interim static variable is implemented.
JS Code
- Func = function () {
- this.test = ' Test ';
- }
- func.acfun= ' net ';
- Console.log (Func.acfun); //net
Two. Instance variable
1. Private instance variables
Within the constructor, variables defined by VAR are private instance variables that can be accessed only within the construct.
JS Code
- var person = Function (value) {
- var age =value;
- This.getage = function () {
- return age;
- }
- }
- Person.prototype._getage = function () {
- return age;
- }
- var yaoming = New Person (' 27 ');
- Console.log (yaoming.age) //undefined
- Console.log (Yaoming.getage ()) //27
- Console.log (Yaoming._getage ()) //defined, the prototype method cannot access age, and only private instance variables can be accessed inside the constructor
2. Public instance variables
Use the properties defined in the constructor or prototype method, as well as the properties defined in the prototype.
The constructor is instantiated with the new operator, a new object is created, the scope of the constructor is assigned to the new object, and the code executes, and if there is this definition property or method in the constructor, the property or method is added to the new object.
JS Code
- var person = Function (name) {
- this.name = name;
- }
- Person.prototype.age = ' 11 ';
- var yaoming = New Person (' ym ');
- Console.log (Yaoming.name);
- Console.log (Yaoming.age); //11
Static private variables for JS simulation