JavaScript closure Comprehension and example _javascript skills

Source: Internet
Author: User
Tags closure script tag
By the way, please indicate:
Lexical scopes: The scope of a variable is determined when it is defined, not when it is executed, that is, the lexical scope depends on the source code, which can be determined by static analysis, so the lexical scope is also called a static scope. With and Eval excepted, so can only say JS scope mechanism is very close to the lexical scope (lexical scope).

Here is a simple example of a closure that uses global variables:
Copy Code code as follows:

var sword= "Hello,welcome to Web front-end development Engineer's blog, please advise." "
function Disword () {
alert (sword);
}
Disword ();

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

The following is an instance of the closure that defines another function in the function:
Copy Code code as follows:

var inum=10;
function Add (num1,num2) {
function Doadd () {return num1+num2+inum;}
return Doadd ();
}

Parsing: The internal function doadd is a closure that gets the value of the incoming parameter num1,num2 and global variable inum, Doadd does not accept arguments, add the last step calls Doadd, and returns two arguments and global variables. You can see that the values used by Doadd are obtained in the execution environment.


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

Copy Code code as follows:

, Case a
/* A piece of code under the Global (window) field * *
function A (i) {
var i;
alert (i);
};
A (10);


Question: What does the above code output?
Answer: 10.
Specific implementation process
The A function has a formal parameter I, when the A function is invoked, the argument 10 is passed, and the formal parameter i=10
Next, define a local variable I with the same name, and not assign a value
Alert Output 10
Think: is the local variable i and formal parameter i the same storage space?
, Case two
Copy Code code as follows:

1/* 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 does the above code output?
Answer: 10,10,2,2
Specific implementation process
The function has a formal parameter I, when the A function is invoked, the argument 10 is passed, and the formal parameter i=10
The first alert puts the value of parameter I at 10 output
The second alert puts the arguments[0] output, which should also be I
Then define a local variable I and assign a value of 2, at which point the local variable i=2
The third alert outputs the value of the local variable I by 2
The fourth alert again argumentsa[0] Output
Think: Can we show that the values of local variable i and parameter I are the same?

, Case three
Copy Code code as follows:

/* A piece of code under the Global (window) field * *
function A (i) {
var i = i;
alert (i);
};
A (10)

Question: What does the above code output?
Answer: 10
Specific implementation process
The first sentence declares a local variable i with the same name as the formal parameter I, and according to the result we know that the latter I is pointing to the
Formal parameter I, so here is equal to the value 10 of the parameter I to assign the local variable i
The second alert, of course, outputs 10.
Thinking: Combined with column two, here is a basic description of the local variable i and parameter I point to the same storage address!
, Case four
Copy Code code as follows:

/* A piece of code under the Global (window) field * *
var i=10;
function A () {
alert (i);
var i = 2;
alert (i);
};
A ();

Question: What does the above code output?
Answer: Undefined, 2
Specific implementation process
First Alert output undefined
Second Alert Output 2
Thinking: What the hell happened?
Looking at a few examples above, you might wonder how it's going to be done. What about the details of the execution? What is the working mode of JS engine?
Parsing process
, execution order
Compiled language, compilation steps are divided into: lexical analysis, syntax analysis, semantic check, code optimization and byte generation.
interpreted language, through lexical analysis and syntactic analysis of the parse tree, you can begin to explain the implementation. Here is a simple primitive about the principle of parsing process, only as a reference, the detailed parsing process (various JS engine and different) still need a further study
The process of JavaScript execution, if a document stream contains multiple script snippets (JS code separated by a script tag or a JS file that is introduced), they run in the following order:
Step 1. Read the first code snippet (the JS execution engine does not execute the program in one line, but a section of the execution)
Step 2. Do lexical analysis and grammar analysis, mistakes are reported grammatical errors (such as parentheses do not match, etc.), and jump to step 5
Step 3. "Pre-resolution" for "VAR" variables and "function" Definitions (never error, because only correct declarations are parsed)
Step 4. Execute code snippet, error errors (such as variable undefined)
Step 5. If you have the next code snippet, read the next code snippet, repeat step 2
Step 6. End
, special instructions
All JS code under the Global Domain (window) field can be viewed as an "anonymous method" that is automatically executed, while other methods within this "anonymous method" are executed when the call is displayed
, key steps
The above process, we are mainly divided into two stages
Parsing: is to construct a legal parsing tree by parsing and pre parsing.
Execution: Execution of a specific FUNCTION,JS engine creates an execution environment (EXECUTIONCONTEXT) and active objects (Activeobject) (they belong to the host object, consistent with the life cycle of the function instance) when executing each instance of the function.
Here are more detailed examples of the analysis of data: http://www.jb51.net/article/24547.htm

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.