Understanding and examples of JavaScript closures

Source: Internet
Author: User
Tags closure script tag

The so-called closures, which are worthy of the lexical representation of functions that include variables that do not have to be computed, that is, the function can use variables defined outside the function.

By the way, please note:

Lexical scope: The scope of a variable is determined at the time of definition rather than execution, meaning that the lexical scope depends on the source code and can be determined by static analysis, so the lexical scope is also called the static scope. With and Eval excepted, so can only say that the scope mechanism of JS is very close to lexical scope (Lexical scope).

The following is a simple closure instance that uses global variables:

1 var sword= "hello,welcome to Web front-end development Engineer's blog, please advise. "
2 function Disword () {
3 alert (SWord);
4}
5 Disword ();

Parsing: When the script is loaded into memory, Disword does not calculate the value of sword, but instead performs a sword calculation when the function Disword called.

The following is a closure instance of the function that defines another function:

1 var inum=10;
2 function Add (num1,num2) {
3 function Doadd () {return num1+num2+inum;}
4 return Doadd ();
5}

Parse: The intrinsic function doadd is a closure, it will get the value of the passed parameter num1,num2 and the global variable inum, Doadd does not accept parameters, add the last step call Doadd, two parameters and global variable sum returned, You can see that the values used by Doadd are obtained in the execution environment.

Here are a few examples on the internet to understand lexical scopes and closures

1. Case 11/* A section of code under the Global (window) field */
2 function A (i) {
3 var i;
4 alert (i);
5};
6 A (10);

Question: What does the above code output?
Answer: 10.

Specific implementation process

    1. A function has a parameter I, which is called when the A function is passed in argument 10, the parameter i=10
    2. Then define a local variable I with the same name, not assigned
    3. Alert Output 10

Think: is the local variable i and parameter i the same storage space?

2. Case 21/* A section of code under the Global (window) field */
2 function A (i) {
3 alert (i);
4 alert (arguments[0]); Arguments[0] should be the formal parameter I
5 var i = 2;
6 alert (i);
7 alert (arguments[0]);
8};
9 A (10);

Question: What will the above code output?
Answer: 10,10,2,2

Specific implementation process

    1. The function has a parameter I, which is called when the A function is passed in argument 10, the parameter i=10
    2. The first alert outputs the value 10 of the parameter I
    3. The second alert arguments[0] output, should also be I
    4. Then define a local variable I and assign a value of 2, this time the local variable i=2
    5. The third alert outputs the value of the local variable i 2
    6. The fourth alert again argumentsa[0] Output

Think: Can this show that the values of the local variable i and the parameter I are the same?

3. Case 31/* A section of code under the Global (window) field */
2 function A (i) {
3 var i = i;
4 alert (i);
5};
6 A (10)

Question: What does the code above output?
Answer: 10

Specific implementation process

    1. The first sentence declares a local variable i with the same name as the parameter I, according to the result we know that the latter I is pointing to the
    2. Parameter I, so here is equal to the value of parameter I 10 assigned local variable i
    3. The second alert, of course, outputs 10.

Thinking: Combined with case two, here basically can explain the local variable i and the parameter I point to the same storage address!

4. Case 41/* A section of code under the Global (window) field */
2 Var i=10;
3 function A () {
4 alert (i);
5 var i = 2;
6 alert (i);
7};
8 A ();

Question: What will the above code output?
Answer: Undefined, 2

Specific implementation process

    1. First Alert output undefined
    2. A second alert output 2

Thinking: What the hell is going on?

Seeing the above examples, you might want to know how to do it. What about the details of the implementation? What is the way the JS engine works?

Parsing process

1. Order of execution

Compiled language, compile steps are divided into: lexical analysis, syntax analysis, semantic inspection, code optimization and byte generation.

interpreted language, with lexical analysis and grammatical analysis of the parse tree, you can begin to interpret the execution. Here is a simple primitive on the principle of the analytic process, only as a reference, the detailed parsing process (various JS engines are different) also need a further study

The execution of JavaScript, if a document flow contains multiple script snippets (JS code separated by the script tag or the introduced JS file), they run in the following order:

    1. Step 1. Read the first code snippet (the JS execution engine does not execute the program one line at a time, but analyzes the execution in a paragraph)
    2. Step 2. Do lexical analysis and grammar analysis, error report syntax errors (such as parentheses mismatch, etc.), and jump to step 5
    3. Step 3. "Var" variables and "function" definitions do "pre-parse" (never error, because only the correct declaration is resolved)
    4. Step 4. Execute code snippet with error (e.g. variable undefined)
    5. Step 5. If there is a next code snippet, read the next code snippet and repeat steps 2
    6. Step 6. End

2. Special Instructions
All JS code in the Global Domain (window) domain can be viewed as an "anonymous method", which is executed automatically, and other methods within this "anonymous method" are executed when the call is displayed.
3. Key steps
The above process, we are mainly divided into two stages

    1. Parsing: It is to construct a legal parsing tree by parsing and pre-parsing.
    2. Execution: Executes a specific FUNCTION,JS engine when each instance of a function is executed, an execution environment (EXECUTIONCONTEXT) and the active object (Activeobject) are created (they belong to the host object and are consistent with the life cycle of the function instance)

Here is a more detailed example of the analysis of data: http://www.alixixi.com/web/a/2010062560089.shtml

Understanding and examples of JavaScript closures

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.