js--Scopes and closures

Source: Internet
Author: User

1. JS is a compiled language, but it is not compiled in advance, the results of the compilation can not be migrated in the distributed system. In most cases, the compilation of JS occurs several microseconds (or even shorter) before the code executes.

2. General steps for compiling
    • Word Segmentation/Lexical Analysis: decomposing a string into lexical units
    • Analytic/syntactic analysis: Transforms lexical units into a syntax tree composed of elements, abstract syntax tree AST
    • Code generation: Converting an AST into a set of machine instructions
3. Three Tools
    • Engine: Controls the process of compiling and executing the entire program
    • Compiler: Responsible for parsing and code generation
    • Scope: Collects and maintains access rights for all declared identifiers
4. The compile process for var a = 2
var a=2; --decomposed into-->

lexical unit

var a = 2; =>

var, A, =, 2

--parse into-->

tree structure

ast

--code generation-->

1. var a: Asks if the scope has a.

2. A = 2: current scope has a,

If there is, assign a value. If not, look up a level of scope for

5. Find two types of lookup in code generation that determine whether a variable exists in a scope
LHS RHS
Intuitive differences Variable on = Left Variable not on = left
Operation Assigning values to variables Take the value of the variable
Can't find them?

1. Strict mode

Throw Referenceerror exception

2. Non-strict mode

Automatically create a global variable implicitly

Throw Referenceerror exception
6. Scope
    • Lexical scopes

Defines the scope in the lexical phase. That is, where to write the variable and block scope when writing the code. The scope of a function is determined entirely by the position at which it is declared

      • global scope                 &NBSP ;                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp         
      • function scope: A scope is created for each function that is declared. A variable or function (identifier) declared within that scope is attached to it and can be used throughout the scope of the function.
      • block Scope
var
 //  variable binding within the function in which it is located  (function  Span style= "COLOR: #000000" > C () { // a is a local variable , b is the global variable  var  a = b = 3;}) () ( function   C () { // a and b are local variables  var  a = 1, b = 3;}) ()
Try/catch
Try {  // exception action     // catch creates a block scope where the variable can only be used in a catch } Catch (Err) {  // Only here can access err}
Let

ES6 newly introduced. Bind a variable in the arbitrary scope {}

In the loop for (Let i = 1; i < 5; i++), I is declared in each iteration, and each iteration is initialized with the value at the end of the previous iteration.

Const ES6 newly introduced, binds the variable in the arbitrary scope {}, and the value is fixed non-modifiable
    • Run-time Modify scope eval, with
7. Scope Nesting

Create a new scope B within a scope A, B is nested in a

b You can access the identifiers in a. A does not have access to identifiers in B

The outermost scope is the global scope

The scope layer is nested to form the scope chain, looking for an identifier when it is accessed, starting from the outermost level, and stopping as soon as it is found, so the outer identifier is masked by the same name as the inner layer.

8. Closures

Closures are explained in various articles, but there seems to be a lot to say. One of the arguments I understand is:

When a function can remember and access its lexical scope, a closure is generated

Function A creates a scope a, declares a function B in a (creates a scope B), returns the function B as a result, and Scope B remembers its scope chain , using B to access the upper scope

9. Loops and closures (an example that seems particularly common)
 for var i = 1; I <= 5; i++) {    setTimeout (function  timer () {        console.log (i);    }, I*1000);}

Description

var i = 1: Defines a global variable

SetTimeout (): Executes the timer function after I seconds. A timer is a callback function that starts calling the For loop when it finishes executing

Result: When the for execution is complete, the timer starts to be called at a frequency of 5 times per second 6

Expect: Output 1,2,3,4,5 per second

Results explained:

SetTimeout did not allow the timer to save a copy of I

When the timer function executes, it will refer to the value of I, when there is only one i=6

Modify the immediate execution

 for (var i = 1; I <=5; i++) {    (function() {        setTimeout (function timer () {            console.log (i);        }, I*1000);}) ();}

Result: output 5 times per second at a frequency of 6

Even if executed immediately, the last variable to be accessed is also the global I

Modify 2--immediate Execution + parameters

 for (var i = 1; I <=5; i++) {    (function(j) {        setTimeout (function timer () {            console.log (i);        }, I*1000);}) (i);}

Result: Output 1,2,3,4,5 per second

Modifying the 3--block scope loop variable

 for (Let i = 1; I <=5; i++) {    setTimeout(function  timer () {        console.log (i);    }, I*1000);}

Result: Output 1,2,3,4,5 per second

Modify 4--Add a variable var j in the Loop

 for (var i = 1; I <=5; i++) {    var j = i;    SetTimeout (function  timer () {        console.log (j);    }, J*1000);}

Result: output 5 times per second at frequency 5 (j and I as global variables, j=5)

modifying 5--block Scope variables

 for (var i = 1; I <=5; i++) {    = i;    SetTimeout (function  timer () {        console.log (j);    }, J*1000);}

Result: Output 1,2,3,4,5 per second

Reference

1. "You don't know the JavaScript" rolled up

2. Also read a lot of on-line instructions, not listed, because did not remember what the specific

js--Scopes and closures

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.