JavaScript lacks block-level scope and does not have a private modifier, but it has a function scope. The benefit of the scope is that internal functions can access the parameters and variables of their external functions (except this and argument. This in the internal function points to the global object, and argument points to the function parameters of the internal function ). We can use this property to simulate private attributes in the object-oriented model.
Copy codeThe Code is as follows: var myObject = function (value ){
Var value = value | 0;
Return {
Increment: function (num ){
Value + = typeof num === 'number '? Num: 0;
},
SetValue: function (num ){
Value = typeof num = 'number '? Num: value;
},
GetValue: function (){
Return value;
}
}
} (10)
// Alert (myObject. getValue (); // 10
MyObject. setValue (20 );
// Alert (myObject. getValue (); // 20
MyObject. increment (5 );
Alert (myObject. getValue (); // 25
In the preceding example, myObjeact is the object returned after an anonymous function is executed. In an anonymous function, the variable value is inaccessible to the external part of the anonymous function, but the internal function can be accessed. The anonymous function execution ends, because the variable value is still accessed by the returned myObject object, the memory occupied by the value is not destroyed. The internal variable value is the same as the private variable of the myObject object.Copy codeThe Code is as follows: var myObject = function (value ){
Var name = 'myobject ';
Return {
Increment: function (num ){
Value + = typeof num === 'number '? Num: 0;
},
SetValue: function (num ){
Value = typeof num = 'number '? Num: value;
},
GetValue: function (){
// Alert (this );
Return value;
},
GetName: function (){
Return name;
},
SetName: function (nameStr ){
Name = nameStr;
},
ToString: function (){
Return '[Object:' + name + ']';
}
}
}
Var obj = myObject (5 );
Obj. increment (6 );
// Alert (obj. getValue (); // 11
// Alert (obj); // [Object: MyObject]
Obj. setName ('temp object 01 ');
Alert (obj) // [Object: temp object 01]