JavaScript lacks a 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 inside function points to the global object, argument the function argument that points to the intrinsic function. We can use this property to simulate private properties in object-oriented objects.
Copy Code code 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
As in the previous example, Myobjeact is the object returned after the anonymous function executes. The variable value in an anonymous function is not accessible to the outside of an anonymous function, but for its internal functions, it is accessible, the anonymous function completes, and the memory occupied by value is not destroyed because the variable value is still accessed by the returned MyObject object. At this point, the internal variable value is the same as the MyObject object's private variable.
Copy Code code 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 ());//One
//alert (obj);//[object:myobject]
Obj.setname (' temp Object 01 ');
Alert (obj)//[object:temp Object]