Original articles, reproduced please specify: JS in the closure of understanding
1.js Closure Package
When developing a project in primary school, the server was developed with node. JS, which encountered the first pitfall of node. JS: A special loop formed by events and callback functions. To solve this problem, I used the method of creating closures, of course, you can use the array's foreach function if you do not need to control the variables of the loop. Recently ES6 in full preparation, the new standard inside the harmony generator and yield very impressive, can also be used to solve the problem. This is something.
Here to highlight the JS closure of this important feature.
First, what is a closure?
1.1 Concept explanation of closures
Closures (Wikipedia): In programming languages, a closure (also lexical closure or function closure) are a function or reference to A function together with a referencing environment-a table storing a reference to each of the non-local variables (also c alled free variables or upvalues) of this function.
In other words, a closure is a reference to a function or function and binds some variables and their living environment.
Consider the concept of closures with two simple uses for the following closures.
1. Extracting variables inside a function
function F1 () {n=999; function f2 () {alert (n); } return F2;} var result=// 999
The function f2 is included inside the function F1, when all local variables inside the F1 are visible to the F2. But the opposite is not possible, F2 internal variables, the F1 is not visible. This is the "chain-scoped" structure (chain scope) that is unique to the JavaScript language. Simply put, a scope chain is a function created at the time of definition, used to find an index of the value of the variable used, and his internal rule is to put the local variables of the function itself in the first place, put the variables in the parent function in the second, put the variables in the higher-level function later, And so on until the global object is reached. When the function needs to query the value of a variable, the JS interpreter will go to the scope chain to find, from the first local variables to find, if not found the corresponding variable, then to the next level of the chain to find, once the variable is found, it will no longer continue. If the desired variable is not found at the end, the interpreter returns undefined. Because of this mechanism, closures can extract variables inside the parent function.
2. Retain certain variables in memory.
function F1 () { var n=999; nadd=function() {n+=1} function F2 () { alert (n); } return F2;} var result=// 999//
First, make it clear that when you define a variable/function inside a function, if you don't use Var, then the variable/function is the global variable/function.
Result is actually the closure F2 function. It runs altogether two times, the first value is 999, the second value is 1000. This proves that the local variable n in the function F1 is kept in memory and is not automatically cleared after the F1 call. Why is that? The reason is that F1 is the parent function of F2, and F2 is assigned to a global variable, which causes F2 to always be in memory, and F2 's presence depends on F1, so F1 is always in memory and will not be reclaimed by the garbage collection mechanism (garbage collection) after the call ends. Here, we need to explain the JS memory recovery mechanism.
In general, a function at the beginning of execution, it will be defined in the variable memory space to save, in case of subsequent statements to use, wait until the function is finished to return, these variables are considered useless. The corresponding memory space is also recycled. The next time the function is executed, all the variables return to their original state and are re-assigned to use. But if another function is nested inside the function, it is possible that the function is called externally. And this inner function uses some variables of the external function. This memory-recycling mechanism can cause problems. If an intrinsic function is called directly after the external function is returned, the intrinsic function cannot read the value of the variable in the external function that he needs. So when the JS interpreter encounters a function definition, it automatically saves the function along with the variables he might use, including the local variables and the variables of the parent and ancestor functions (the free variables), which is to build a closure that will not be recycled by the memory collector, only if the internal function cannot be called ( For example, if it is deleted, or without a pointer), the closure will be destroyed, and none of the variables referenced by the closure will be recycled when the next memory recycle starts.
3. Implementing Object Encapsulation
varperson =function(){ //variable scope is inside function, external unreachable varName = "Default"; return{getName:function(){ returnname; }, SetName:function(newName) {name=NewName; } } }(); Print (person.name);//direct access with a result of undefinedprint (Person.getname ()); Person.setname ("Abruzzi"); Print (Person.getname ()); The results are as follows: undefineddefaultAbruzzi
This is a simple JS object encapsulation, only through the object can access the variables in the object, the implementation of variables and environment (object) binding. That is, through closures, we simulate the template of encapsulated objects in object-oriented languages.
4. Efficient anonymous self-executing function
var datamodel = { table: [], tree: {} }; (function(DM) { for (var i = 0; i < dm.table.rows;i++) { var row = dm.table.rows[i]; for (var j = 0; j < row.cells; i++) { Drawcell (i, j); } } // Build Dm.tree
The closure in the code is actually used to do the initialization of the UI, after the execution of the temporary variable is destroyed, such a mechanism does not pollute the global variables, efficient.
1.2 Closure and the concept of anonymous function identification
First look at the concept of anonymous functions:
anonymous function (Wikipedia): In computer programming, an anonymous function (also function literal or lambda abstraction) is a function definition, which is not bound to an identifier.
Simply put, a function without an identifier is an anonymous function. Here are some of the anonymous functions:
(function() {}) (); most common to; ( function (){}()); void function () {}; the wrong wording function
The principle and understanding of anonymous functions is not to be mentioned here. We only explore the relationship between anonymous functions and closures.
Recall the keyword in the concept of closures-"is a function or reference to a function", stating that functions that are declared within a function are closures, regardless of function. So, come to the conclusion that:
If the anonymous function is not inside the function, it is not a closure.
The anonymous function in the function if it references the variable of the parent function, then the anonymous function becomes a closed packet.
It's so Simple "( ̄▽ ̄)" ". Therefore, the following definition of closures is generated:
var datamodel = { table: [], tree: {} }; (function(DM) { //something
Reference: JavaScript in-depth understanding closure-script house, Tomb of No one, Sunlylorn, 10 fleeting.
The closure comprehension in JS