JavaScript has no private members, but there are private variables, all of which are public.
Any variable defined in a function can be considered a private variable because it cannot be accessed inside the function.
Private variables include: arguments to functions, local variables, other functions defined inside functions
-Define private variables and private functions in a private scope
function MyObject () { // private variables and private functions var Privatevariable=10; function Privatefunction (params) { return false " // privileged method ——— -Methods that have access to private variables and private functions this . Publicmethod= function () {privatevariable ++; return Privatefunction}}
Private variables and functions are defined in the constructor, and privileged methods that can access private variables and functions are created.
functionPerson (name) { This. GetName =function() { returnname; }; This. SetName =function(value) {Name=value; };}varperson =NewPerson ("Candy"); alert (Person.getname ()); //"Candy"Person.setname ("Greg"); alert (Person.getname ()); //"Greg"varPerson2 =NewPerson ("Tong"); alert (Person2.getname ()); //"Tong"
It is not possible to access name directly through the person object, the person object does not have the name attribute
The name can be accessed through a function, because the active object of the person () is also in GetName, SetName's scope of action ([[Scope] property), is not destroyed, and the function accesses the variable name of the person () activity through the action chain domain.
-use constructors to define the disadvantages of private variables and private functions in a private scope
Each time the object is created, the same set of new variables and new methods are created, but the methods are the same, and there is no need to create new methods.
-Workaround
Implemented with static private variables
JavaScript defines private variables and private functions in a private scope (1)