The benefit of this is that inner functions can access the parameters and variables of the outer function in which they are defined.
First, let’s construct a simple object.
var testObj = {
value: 10,
add: function(inc){
this.value = (typeof inc === "number") ? inc : 1;
}
};
testObj.add();
testObj.value; // 11
testObj.add(2);
testObj.value; // 13
There is a problem with writing this way. The value cannot be guaranteed not to be illegally modified. It can be modified as follows .
var testObj = (function(){
var value = 10;
return {
add: function(inc){
value = (typeof inc === "number") ? inc : 1;
},
getValue: function (){
return value;
testObj.add();
testObj.getValue(); // 11
testObj.add(2);
testObj.getValue(); // 13
We can generally call a function to initialize testObj. The function will return an object literal. The function A value variable is defined here, which is always available to the add and getValue methods, but the scope of the function makes it invisible to other programs. At the same time, we can also draw a conclusion that the internal function has a longer life cycle than its external function.
Let’s continue looking at an example of constructor calling.
MyObj.prototype.getStatus = function(){
return this.status;
};
var obj = new MyObj("javascript");
obj.getStatus(); // "javascript"
There is nothing wrong with writing this, but it will be a bit "unnecessary", why? What about using a getStatus method to access a property that can be accessed directly? Of course it only makes sense if status is a private property.
return status;
}
};
};
var myObj = obj("javascript");
myObj.getStatus(); // "javascript"
Here when we call obj, it returns a new object containing the getStatus method , a reference to the object is saved in myObj, even if obj has been returned, the getStatus method still enjoys the privilege of accessing the status attribute of the obj object. The getStatus method does not access a copy of the parameter, it accesses the parameter itself. This is possible because the function has access to the context in which it was created, which is called a closure.