Closure in Javascript 1. What is a Closure? The "official" explanation is: the so-called "closure" refers to an expression (usually a function) with many variables and an environment bound to these variables ), therefore, these variables are part of the expression. I believe that few people can directly understand this sentence, because he described it too academic. I want to use how to create a closure in Javascript to tell you what a closure is, because it is very difficult to understand the definition of a closure directly by skipping the process of creating a closure. See the following code: function a () {var I = 0; function B () {alert (++ I) ;}return B ;}var c = (); c (); this code has two features: 1. function B is nested in function a; 2. function a Returns function B. In this way, after var c = a () is executed, variable c actually points to function B and then executes c () then a window will pop up showing the I value (the first time is 1 ). This Code actually creates a closure. Why? Because variable c outside function a references function B in function a, that is, when function B inside function a is referenced by a variable outside function, A closure is created. 2. Another example is to simulate the private variable functionCounter (start) {var count = start;
Return {
Increment: function (){
Count ++;
},
Get: function (){
Return count;
}
}
}
Var foo = Counter (4 );
Foo. increment ();
Foo. get (); // 5 here, the Counter function returns two closures, the increment function and the get function. Both functions maintain reference to Counter in the external scope, so you can always access the variable count defined in this scope. edit the closure in objective c's closure (block) objective c in this grammar, which is implemented through block. Apple expands Block syntax in C, Objective-C, and C ++ and supports it in GCC4.2. You can understand it as a function pointer, anonymous function, closure, and lambda expression. Here, block objects are used for the time being, because there are still some differences between them. Declare a block. If you use a block object in inline mode, you do not need to declare it. The block object declaration syntax is similar to the function pointer declaration syntax, but the block object should use the Escape Character (^) instead of the asterisk pointer (*). The following Code declares an aBlock variable that identifies a block that requires three parameters and has a float return value. Float (^ aBlock) (const int *, int, float); l creates a block and uses the delimiters (^) as the start flag and semicolons as the end flag. The following example declares a simple block and assigns it to the block variable (oneFrom) previously declared ). Int (^ oneFrom) (int); oneFrom = ^ (int anInt) {return anInt-1 ;}; 2. What is the function of closure? In short, the function of the closure is that after a executes and returns, the closure makes the garbage collection mechanism of Javascript GC not to reclaim the resources occupied by, because the execution of the internal function B of a depends on the variables in. This is a straightforward description of the function of the closure, which is neither professional nor rigorous, but probably means that the process of understanding the closure needs to be gradual. In the above example, because of the existence of the closure, the I in a always exists after function a returns, so that each execution of c (), I is the value of alert after auto-increment 1. Then let's imagine another situation. If a does not return function B, the situation is completely different. Because after a is executed, B is not returned to the external world of a, but is referenced by a. At this time, a will only be referenced by B, therefore, functions a and B are referenced by each other without being disturbed by the outside world (referenced by the outside world), and functions a and B are recycled by GC. (The garbage collection mechanism of Javascript will be described in detail later.) 3. a more in-depth understanding of the micro-world in the closure, such as the relationship between closure and nested function a and nested function B, we need to introduce several other concepts: execution context, call object, scope, and scope chain ). The process from definition to execution of function a is used as an example to describe these concepts. 1. When defining function a, the js interpreter sets the scope chain of function a to the "Environment" of function a when defining function ", if expression a is a global function, the scope chain contains only window objects. 2. When function a is executed, function a enters the corresponding execution environment (execution context ). 3. In the process of creating the execution environment, a scope attribute, that is, the scope of a, is added for a, and its value is the scope chain in step 1. That is, the scope chain of a. scope =. 4. A call object is created in the execution environment ). An activity object is also an object with attributes, but it does not have a prototype and cannot be directly accessed through JavaScript code. After creating the activity object, add the activity object to the top of the scope chain of. In this case, the scope chain of a contains two objects: The activity object of a and the window object. 5. The next step is to add an arguments attribute to the activity object, which stores the parameters passed when calling function. 6. Add the parameters of all function a and the reference of function B to the activity object of function. In this step, the definition of function B is completed. As in step 1, the scope chain of function B is set to the environment defined by B, that is, the scope of function. At this point, the steps from definition to execution of function a are completed. At this time, a returns the reference of function B to function c, and the scope chain of function B contains the reference to the activity object of function, that is to say, B can access all variables and functions defined in. Function B is referenced by Function c, and function B is dependent on function a. Therefore, function a is not recycled by GC after return. When function B is executed, it will be the same as the above steps. Therefore, during execution, B's scope chain contains three objects: B's activity object, a's activity object, and window object, as shown in :, when function B accesses a variable, the search order is to first search for its own activity objects. If it exists, it returns. If it does not exist, it will continue to search for the activity object of function, search by time until it is found. If the entire scope chain cannot be found, undefined is returned. If function B has a prototype object, search for its own prototype object after searching for its own activity object. This is the Variable Search Mechanism in Javascript. Iv. Closure Application Scenario 1. Protection of variable security in functions. Taking the initial example as an example, in function a, I can only access function B, but cannot access function B through other channels, thus protecting the security of I. 2. Maintain a variable in the memory. Still, for example, because of the closure, the I in function a is always in the memory, so each execution of c () will add 1 to the I self. The above two points are the most basic application scenarios of closures. Many classic cases are based on this. 5. The garbage collection mechanism of Javascript is in Javascript. If an object is no longer referenced, it will be recycled by GC. If two objects are referenced by each other and no longer referenced by 3rd, the two objects referenced by each other will be recycled. Because function a is referenced by function B and function B is referenced by Function c outside of function a, this is why function a is not recycled after execution.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.