Home  >  Article  >  Web Front-end  >  JavaScript uses closures to simulate private properties of objects_javascript tips

JavaScript uses closures to simulate private properties of objects_javascript tips

WBOY
WBOYOriginal
2016-05-16 17:57:511196browse

JavaScript lacks block-level scope and has no private modifier, but it does have function scope. The benefit of scope is that inner functions can access the parameters and variables of their outer functions (except this and argument. This in the inner function points to the global object, and argument points to the function parameters of the inner function). We can use this property to simulate private properties in object-oriented.

Copy code The 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

As in the above example, myObject is returned after execution of the anonymous function object. The variable value in the anonymous function is inaccessible to the outside of the anonymous function, but it is accessible to the functions inside it. The execution of the anonymous function ends. Since the variable value is still accessed by the returned myObject object, value is occupied by it. The memory is not destroyed. At this time, the internal variable value is just like the private variable of the myObject object.
Copy code The 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]
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn