JS closure (jquery Ajax asynchronous multi-cycle application)

Source: Internet
Author: User
JS closure (reprinted) 1. What is a closure?
The official explanation is that a closure is 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. In fact, all functions in JavaScript are closures. But in general, nested functions produce more powerful closures, which are also called "closures" in most cases ". See the following section. Code :

Function (){
VaR I = 0;
Function B (){
Alert (++ I );
}
Return B;
}
VaR c = ();
C ();
This code has two features:

Function B is nested in function;
Function a Returns function B.

In this way, after var c = a () is executed, variable C actually points to function B, variable I is used in B, and then C () is executed () 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 a's internal function B is referenced by a variable outside function a, a closure is created ".

Let's be more thorough. The so-called "closure" refers to defining another function in the constructor as the method function of the target object, and the method function of this object references temporary variables in the outer function body in turn. This allows the target object to indirectly retain the temporary variable value used by the original constructor as long as it can maintain its method throughout the lifetime. Although the call to the initial constructor has ended, the name of the temporary variable has also disappeared, but the value of the variable can always be referenced in the method of the object, this value can only be accessed in this way. Even if the same constructor is called again, only new objects and methods are generated. The new temporary variables only correspond to new values, which are independent of those called last time.

To better understand closures, let's continue to explore the functions and effects of closures.

2. What are the functions and effects of closures?
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)

Iii. microview of closures
To learn more about closures and the relationship between function a and nested function B, we need to introduce several other concepts: the function execution environment (excution context), and the activity object (call object) scope and scope chain ). The process from definition to execution of function a is used as an example to describe these concepts.

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.
when function a is executed, function a enters the corresponding execution environment (excution context ).
during the creation of the execution environment, a scope attribute, that is, the scope of A, is added for A. The value is the scope chain in step 1. That is, the scope chain of A. Scope =.
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.
the next step is to add an arguments attribute to the activity object, which stores the parameters passed when function a is called.
Finally, add the parameters of all function a and reference of internal 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 complete. 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.
4. Use Cases of closures
to protect 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.
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.
by protecting the security of variables, JavaScript private attributes and private methods (cannot be accessed externally) are recommended: http://javascript.crockford.com/private.html
private properties and methods cannot be accessed outside of constructor

Function Constructor (...){
VaR that = this;
VaR membername = value;
Function membername (...){...}
}
The above three points are the most basic application scenarios of closures. Many classic cases are based on this. //************************************** ****************************************

 //  Back to price list  
VaR Loadpricelist = Class ($ _ $ ,{
Creat: Function (){},
Loadpricelist: Function (){
VaR J = $ ("Div [Lang]"). Get (),
_ J = J. length,
K = math. Ceil (_ j/5 ),
L = [],
Tt = [],
M, N, O,;
For (M = 0; m <K; m ++ ){
If (M <k ){
N = J. Slice (0, 5 );
L. Push (N );
J. splice (0, 5)
}
}
For (O = 0; O <K; O ++ ){
VaR B;
For (B = 0; B <L [O]. length; B ++ ){
VaR P = L [O] [B]. Lang;
Ajaxplist (P)
}
}
}
})
Function Ajaxplist (p ){
VaR Repeated r = P. Split ("| ");
$. Ajax ({
Async: True ,
Type: "Get ",
URL: region R [1],
Datatype: 'html ',
Cache:False ,
Error: Function (){
},
Success: Function (HTML ){
$ ("# Price _" + export r0000000000000.html (HTML );
}
});
}

1. What is a closure?
The official explanation is that a closure is 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. In fact, all functions in JavaScript are closures. But in general, nested functions produce more powerful closures, which are also called "closures" in most cases ". See the following code:

Function (){
VaR I = 0;
Function B (){
Alert (++ I );
}
Return B;
}
VaR c = ();
C ();
This code has two features:

Function B is nested in function;
Function a Returns function B.

In this way, after var c = a () is executed, variable C actually points to function B, variable I is used in B, and then C () is executed () 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 a's internal function B is referenced by a variable outside function a, a closure is created ".

Let's be more thorough. The so-called "closure" refers to defining another function in the constructor as the method function of the target object, and the method function of this object references temporary variables in the outer function body in turn. This allows the target object to indirectly retain the temporary variable value used by the original constructor as long as it can maintain its method throughout the lifetime. Although the call to the initial constructor has ended, the name of the temporary variable has also disappeared, but the value of the variable can always be referenced in the method of the object, this value can only be accessed in this way. Even if the same constructor is called again, only new objects and methods are generated. The new temporary variables only correspond to new values, which are independent of those called last time.

To better understand closures, let's continue to explore the functions and effects of closures.

2. What are the functions and effects of closures?
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)

Iii. microview of closures
To learn more about closures and the relationship between function a and nested function B, we need to introduce several other concepts: the function execution environment (excution context), and the activity object (call object) scope and scope chain ). The process from definition to execution of function a is used as an example to describe these concepts.

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.
when function a is executed, function a enters the corresponding execution environment (excution context ).
during the creation of the execution environment, a scope attribute, that is, the scope of A, is added for A. The value is the scope chain in step 1. That is, the scope chain of A. Scope =.
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.
the next step is to add an arguments attribute to the activity object, which stores the parameters passed when function a is called.
Finally, add the parameters of all function a and reference of internal 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 complete. 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.
4. Use Cases of closures
to protect 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.
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.
by protecting the security of variables, JavaScript private attributes and private methods (cannot be accessed externally) are recommended: http://javascript.crockford.com/private.html
private properties and methods cannot be accessed outside of constructor

function Constructor (...) {
var that = This;
var membername = value;
function membername (...) {...}
}< br> the above three points are the most basic application scenarios of closures. Many classic cases are based on this.

Related Article

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.