•Simulate block-level scope
Everyone knows that there is no concept of block-level scope in JavaScript. We can simulate block-level scope by using closures. See the following example:
(function () {
for (var i = 0; i < 10; i ) {
//Do Nothing
}
alert(i); //Output 10
})();
Line 6 can access for The variable i in the loop block, if we slightly modify the above code and place the for loop block in the closure, the situation is different:
(function () {
(function () {
for (var i = 0; i < 10; i ) {
//Do Nothing
}
})();
alert(i); //Error: 'i' is undefined
})();
When accessing changed i in line 8, an error occurred, achieving the block-level scope we wanted.
•Private properties
There is no concept of block-level scope in JavaScript, and there is also no concept of private properties, but there are private variables. What if we want to encapsulate and hide some data? You may have thought that you can implement the private properties of an object by using closures and private variables.
<1>. Instance private attributes
The characteristic of instance private attributes is that each object will contain independent attributes, and there is no sharing between objects. In order to achieve this goal, you can add a private variable in the constructor and then define a public method to access this private variable, just like the setters and getters in other OO languages. The following example implements the private properties of the instance:
//Instance private variable
function MyObject(name) {
//Define private variables
//Note: this.name is not used here. If this.name is used, it becomes a public property
var privateName = name;
//Define private familiarity
var privateFunction = function () {
return "Private Function";
}
//Public method access private familiarity
MyObject.prototype.getName = function () {
return privateName;
}
MyObject.prototype.getFunction = function () {
return privateFunction();
}
}
var moGyy = new MyObject("gyy");
alert (moGyy.getName()); //Output gyy
alert(moGyy.getFunction()); //Output Private Function
var moCyy = new MyObject("cyy");
alert(moCyy. getName()); //Output cyy
alert(moCyy.getFunction()); //Output Private Function
getName of the two objects moGyy and moCyy created in the above example Return different values, and if you want to call private methods, you also need a public interface. In the above example, the reason why the two public functions can access private variables is because the two public functions are closures, and the scope chain of the closure contains the variable object containing the function. Therefore, when searching for variables, the A scope chain allows access to private variables in the containing function. In the above example, public methods are added to the prototype of MyObject to prevent two function instances with the same function from being created every time the object is created.
<2>. Static private attributes
In some cases we may want the data to be shared globally, then static attributes may be used. We still want this attribute to be private, so how to implement static private attributes? ? First of all, this private should be outside the constructor. In order to integrate the variables outside the constructor and the constructor, you can use a closure to include both the private variables and the constructor in its scope. In order to access the internal variables outside the closure Constructor, you can use a global variable to refer to the constructor, as shown in the following code example:
//Static private variables and instance private variables
(function () {
//Define private variables
var staticPrivateValue = "";
//Constructor, constructor Assign the weaving function to a global variable
MyObject = function (name) {
//Define instance variables
this.name = name;
};
//Define two public methods For accessing private variables, add public methods to the prototype again
MyObject.prototype.getPrivateValue = function () {
return staticPrivateValue;
}
MyObject.prototype.setPrivateValue = function (value ) {
staticPrivateValue = value;
}
})();
var mo = new MyObject("jeff-gyy");
mo.setPrivateValue("gyycyy"); / /Set the value of the private attribute
alert(mo.getPrivateValue()); //Output gyycyy
alert(mo.name); //Output jeff-gyy
var mo1 = new MyObject("jeff- cyy");
alert(mo1.getPrivateValue()); //Output gyycyy
alert(mo1.name); //Output jeff-cyy
From the above code See, the value returned by mo1 when calling the getPrivateValue function is the value "gyycyy" set by mo. Why is this? First, we define an anonymous function and call the function immediately. The function contains the private variable staticPrivateValue. Then the two prototype methods defined for MyObject can actually access the private variables in the containing function through the scope chain of the closure, that is, getPrivateValue and setPrivateValue. The scope chain of both functions contains the variable object of the anonymous function. We know that the variable object contained in the scope chain is actually a pointer, so when the two objects created use the public method to house the private variable, they actually access both It is the staticPrivateValue in the variable object of the anonymous function, so it can be shared between variable instances. From the perspective of traditional OO languages, the static properties we implement are not actually static in the true sense, but only realize the sharing of static property instances.
<3>. Module mode and enhanced module mode
Another way to share data globally is singleton. You can use the module mode to implement the singleton mode of the Object type, or you can use the enhanced module mode to implement customization. Singleton pattern of type, as shown in the following example:
//Since Define constructor
var mo = new function () {
//Private variable
var privateValue = "";
//Normal module mode
return {
publicValue: "public ",
//Access private variables
getPrivateValue: function () {
return privateValue;
},
setPrivateValue: function (value) {
privateValue = value;
}
}
}();
mo.setPrivateValue("private value");
alert(mo.getPrivateValue());
alert(mo.publicFunction());
The module mode uses anonymous functions to encapsulate the internal implementation. In the above example, the anonymous function contains the private variable privateValue. The public functions in the returned object access the included function through the scope chain of the closure. Private variables, since the defined anonymous function is called immediately, the variable mo refers to the returned object. The above singleton pattern returns an Object object. You can use the enhanced module pattern to implement a custom type of singleton pattern:
//Enhanced module mode
//Custom constructor
function MyObject(name) {
this.name = name;
} ;
//Custom constructor
var mo = new function () {
//Private variable
var privateValue = "";
//Enhanced module mode
var o = new MyObject("gyycyy");
o.publicValue = "public";
//Access private variables
o.getPrivateValue = function () {
return privateValue;
}
o.setPrivateValue = function (value) {
privateValue = value;
}
return o;
}();
mo.setPrivateValue("private value");
alert(mo.getPrivateValue());
alert(mo.publicFunction());
The above code example implements the singleton mode of MyObject.
The last thing that needs to be mentioned is that there are advantages and disadvantages to using closures. Since the closure scope chain refers to the variable object containing the function, it will occupy additional memory, and the variable search also needs to go through the scope chain, so it will It consumes search time, and the situation is more serious the deeper the closure. In addition, in IE (earlier versions), because the garbage collection mechanism uses reference counting, circular references may occur, leading to memory leaks, as shown in the following example:
function assignHandler(){
var element = document.getElementById("someElement");
element.onclick = function( ){
alert(element.id);
};
}
In the above code, a closure is created as an event of element. The closure refers to the variable object containing the function assingHandler. It is the reference to the variable object that makes the element reference count at least 1, so element will not be recycled, causing memory leaks. You can think of ways to modify it.