Understanding and examples of javascript closures

Source: Internet
Author: User

Note:
Lexical scope: the scope of a variable is determined during definition rather than execution. That is to say, the lexical scope depends on the source code and can be determined through static analysis. Therefore, the lexical scope is also called static scope. Except with and eval, we can only say that the JS scope mechanism is very close to the Lexical scope ).

The following is a simple example of closure using global variables:
Copy codeThe Code is as follows:
Var sWord = "Hello, Welcome to the blog of web Front-end development engineers. Please give me more advice. "
Function disWord (){
Alert (sWord );
}
DisWord ();

Parsing: When the script is loaded to the memory, disWord does not calculate the sWord value, but the sWord is executed when the function disWord is called.

The following example defines the closure of another function in the function:
Copy codeThe Code is as follows:
Var iNum = 10;
Function add (num1, num2 ){
Function doAdd () {return num1 + num2 + iNum ;}
Return doAdd ();
}

Resolution: the internal function doAdd is a closure that gets the values of the passed num1, num2, and global variable iNum. doAdd does not accept the parameter. add calls doAdd In the last step, return the sum of the two parameters and global variables. We can see that the values used by doAdd are obtained in the execution environment.


Below are several examples found on the Internet to understand the lexical scopes and closures.

Copy codeThe Code is as follows:
Case 1
/* A piece of code in the global (window) Field */
Function a (I ){
Var I;
Alert (I );
};
A (10 );


Q: What will the above Code output?
Answer: 10.
Specific execution process
Function a has an I parameter. When function a is called, input 10 arguments. The I parameter is 10.
Next, define a local variable I with the same name without assigning a value.
Alert output 10
Thinking: is the local variable I and the shape parameter I the same bucket?
Case 2
Copy codeThe Code is as follows:
1/* a piece of code in the global (window) Field */
2 function a (I ){
3 alert (I );
4 alert (arguments [0]); // arguments [0] should be the form parameter I
5 var I = 2;
6 alert (I );
7 alert (arguments [0]);
8 };
9 a (10 );

Q: What will the above Code output?
Answer: 10, 10, 2, 2
Specific execution process
The function has an input parameter I. When calling function a, input the input parameter 10, and the input parameter I = 10.
The first alert outputs the value of I 10.
The second alert outputs arguments [0], which should also be I
Then define a local variable I and assign it to 2. At this time, the local variable I = 2
The third alert outputs the value 2 of the local variable I.
The fourth alert outputs argumentsa [0] again.
Thinking: Can the local variable I and the parameter I have the same value?

Case 3
Copy codeThe Code is as follows:
/* A piece of code in the global (window) Field */
Function a (I ){
Var I = I;
Alert (I );
};
A (10)

Q: What will the above Code output?
Answer: 10
Specific execution process
The first clause declares a local variable with the same name as the form parameter I. According to the result, we know that the next I point
This is equivalent to assigning the value 10 of the parameter I to the local variable I.
The second alert will certainly output 10
Thinking: Combined with Case 2, here we can basically show that the local variable I and the form parameter I point to the same storage address!
Case 4
Copy codeThe Code is as follows:
/* A piece of code in the global (window) Field */
Var I = 10;
Function (){
Alert (I );
Var I = 2;
Alert (I );
};
A ();

Q: What will the above Code output?
Answer: undefined, 2
Specific execution process
The first alert outputs undefined
The second alert output 2
Think: What's the problem?
When you see the examples above, you may wonder how to execute them? What are the execution details? How does the JS engine work?
Parsing process
, Execution sequence
The compilation steps include lexical analysis, syntax analysis, semantic check, code optimization, and byte generation.
After obtaining the syntax analysis tree through lexical analysis and syntax analysis, the interpreted language can start to be executed. Here is a simple and original principle of the parsing process. It is only for reference. The detailed parsing process (different JS engines) also requires further research.
Javascript execution process. If a Document Stream contains multiple script code segments (javascript code separated by the script tag or the introduced js file), the running sequence is as follows:
Step 1. Read the first code segment (the js execution engine does not execute the program in one row, but analyzes and executes the program in one row)
Step 2. Perform lexical analysis and syntax analysis. If there is a mistake, the system reports a syntax error (such as mismatched brackets) and jumps to Step 5.
Step 3. Perform "pre-resolution" on the [var] variable and [function] definition (no error will be reported because only the correct declaration is parsed)
Step 4. Execute the code segment. If there is an error, an error is returned (for example, the variable is undefined)
Step 5. If there is another code segment, read the next code segment and repeat Step 2.
Step 6. End
, Special instructions
All JS code in the window field can be regarded as an "anonymous method" and will be automatically executed, other methods in this "anonymous method" are executed only when they are displayed and called.
Key steps
The above process is divided into two phases.
Parsing: A Legal syntax analysis tree is constructed through syntax analysis and pre-resolution.
Execute: execute a specific function. When the JS engine executes each function instance, it creates an execution environment (ExecutionContext) and an activity object (activeObject) (they belong to the Host object, is consistent with the life cycle of the function instance)
Here are more detailed examples of analytics: http://www.jb51.net/article/24547.htm

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.