Similar to the usage of keywords such as private, protected, and public in class-based object-oriented languages such as java, the object-based JavaScript language also has similar member visibility issues in object construction. The visibility definitions of JavaScript Object structures can be divided into the following types:
1. private properties)
The var keyword defines the scope of the variable in the object construction. The variable can only be accessed within the scope of the object construction method. For example:
The Code is as follows:
Function VariableTest ()
{
Var myVariable; // private
}
Var vt = new VariableTest ();
Vt. myVariable; // The undefined exception occurs.
2. private methods)
Similar to private attributes, the object can only be accessed within the scope of the object constructor. For example:
The Code is as follows:
Function MethodTest ()
{
Var myMethod = function () // private
{
Alert ("private method ");
}
This. invoke = function ()
{
// Access myMethod
Mymehtodd ();
}
}
Var mt = new MethodTest ();
Mt. myMethod (); // error. If you use trycatch, you can catch an exception in "The object does not support this attribute or method ".
Mt. invoke ();
3. public properties)
There are two ways to define public attributes:
(1) defined by the this keyword. For example:
The Code is as follows:
Function PrivilegedVariable ()
{
This. variable = "privileged variable ";
}
Var pv = new PrivilegedVariable ();
Pv. variable; // return "privileged variable"
(2) It is defined by the prototype of the constructor. For example:
The Code is as follows:
Function PublicVariable (){}
PublicVariable. prototype. variable = "public variable ";
Var pv = new PublicVariable ();
Pv. variable; // return "public variable"
4. public methods)
Likewise, there are two ways to define public methods.
(1) defined by the this keyword. (2) It is defined by the prototype of the constructor.
It is omitted here ...........
5. static properties)
Attributes directly added for the object constructor cannot be accessed by the object instance and can only be used by the constructor itself. For example:
The Code is as follows:
Function StaticVariable (){}
StaticVariable. variable = "static variable ";
Var sv = new StaticVariable ();
Sv. variable; // return "undefined"
StaticVariable. prototype. variable; // return "undefined"
StaticVariable. variable; // return "static variable"
6. static methods)
Methods directly added for the object constructor cannot be accessed by the object instance and can only be used by the constructor itself.
Code omitted ........