A public method that has the permission to access private variables and private functions is called a privileged method. There are two methods to create a privileged method on an object.
First, define the privileged method directly in the constructor. The basic mode is as follows:
Function myobject () {var privatevariable = 10; function privatefunction () {alert (1);} This. publicmethod = function () {privatevariable ++; return privatefunction () ;}// privileged method} var AA = new myobject (); AA. publicmethod ();
This. as the closure of the myobject function, the publicmethod method has the right to access the variables and methods defined in the constructor. In the AA instance, in addition to the publicmethod, there is no other way to directly access privatevariable and privatefunction (). In this instance
Publicmethod () is one of the privileged methods of the constructor myobject.
One disadvantage of defining a privileged method in a constructor is that the constructor mode must be used for this purpose. The constructor mode has the disadvantage that each instance creates the same set of new methods.
Static private variable
You can also create privileged methods by defining private variables or functions in a private scope. The basic mode is as follows:
(function(){ var praviteVariable = 10; function praviteFunction(){ return false; } MyObject = function(){ } MyObject.prototype.publicMethod = function(){ privateVariable++; return privateFunction(); }})();
In this mode, a private scope is created, which encapsulates a constructor. The public method uses the prototype definition. In this mode, the constructor does not use function declaration or VaR when declaring myobject, therefore, because uninitialized variables always create a global variable, myobject becomes a global variable and can be accessed outside the private scope.
The main difference between this mode and the constructor's definition of privileged methods is that private variables and functions in this method are shared by instances, because this privileged method is defined in prototype, therefore, all instances use the same function, but because this privileged method is used as a closure, this closure always contains a reference to the scope, the consequence is that the variables referenced by each created instance are the same, that is, no matter which instance changes the value of the variable, the value of this variable in other instances will also be changed, because this privileged method always saves the effect on the include scope.
About private variables, static private variables