ES6 let (understanding closures) and Const commands

Source: Internet
Author: User

ES6 Let (understanding closures) and Const commands

Recently, the process of doing the project, the use of ES6, because few contact before, so the use is not familiar. Therefore purchased the Nanyi Teacher's ES6 standard introduction, here Thanks Nanyi Teacher's book.

We know that ECMAScript 6, ES6, is the fifth version of ECMAScript because it was officially released in June 2015, so it became ECMAScript2015. The main purpose of ES6 is to be JS for writing complex large-scale applications and becoming an enterprise-class development language.

Note: Because sometimes we want to know the specific implementation of ES6 code or hope to be able to convert to ES5 use, we can use the http://babeljs.io/to achieve online ES6 code into ES5 code.

First part: let command I. Block-level scope ( emphasis ).

We know that there are only global scopes and function scopes in JavaScript, and there is no block-level scope. In this way, there are some problems when you use them. Let's start with an example of the use of the Let block level scope.

Example 1:

The code looks like this:

        {            var a=5;            Let b=10;        }        Console.log (a);        Console.log (b);

The results we get from the console are as follows:

In other words, Var declares a variable that can be called in the global environment because there is no block-level scope, and a let-declared variable cannot be called in the global environment because of a block-level scope.

 

 Example 2: This example is a very classic example.

  

        var a=[];          for (var i=0;i<10;i++) {            a[i]=function() {                console.log (i);}            ;        }        a[//ten    
    var a=[];      for (Let i=0;i<10;i++) {        a[i]=function() {            console.log (i);        };    }    a[6] ();    // 6    

As we can see, the only difference between the two examples is that the former for loop uses Var to define I, and the result is 10. The latter uses let to define I, and the result is 6. What is this for? Nanyi's explanation in the book is not very clear, so I will post a personal opinion:

On this issue, on the surface is really not very good understanding, query a lot of information, many people talk about a lot of obscure knowledge, seems very tall, but it is not difficult, the following according to my understanding to explain, if there is a problem, welcome criticism, if you can some harvest will be better.

  example Two former (var i) specific implementation process is as follows:

var a=[];


var i=0;//declares the variable i because of Var, so the for Loop code block does not have a block-level scope, so I is considered a global variable and placed directly in the global variable.
A[0]=function () {
Console.log (i);//The reason I is I instead of 0 is because we just define the function, not called, so we do not enter the function execution environment, I certainly do not follow the scope chain up search to find the value of I.
}//The function definition is a global scope because it does not have a block-level scope.


var i=1;//the second cycle, at this time Var i=1, covering the preceding var i=0; now I is 1;
A[1]=function () {
Console.log (i);//interpret the same a[0] function.
}


var i=2;//the third cycle, at this time i=2, in the global scope, so covered the front of the I=1;
A[2]=function () {
Console.log (i);
}


...... The fourth cycle is now i=3 this and the following I constantly overwrite the i in front, because all are in the global scope
...... Fifth cycle at this time i=4
...... Sixth cycle at this time i=5
...... Seventh cycle at this time i=6
...... Eighth cycle at this time i=7
...... Nineth cycle at this time i=8


var i=9;
A[9]=function () {
Console.log (i);
}


var i=10;//at this point I is 10, because the loop condition is not met, so the loop is stopped .

It continues to execute down in the global environment immediately thereafter.

A[6] ();//Call the a[6] function at this point, and then enter the execution environment of the a[6] function , i.e. a[6]=function () {Console.log (i)}; The code in the execution function console.log (i); Because the variable i does not exist in the function execution environment, it is now looked up along the scope chain ( See my post, "deep understanding scope and scope chain "), which goes into the global scope to look for the variable i, In the global scope, i=10 covers all of the previous I values, so I is ten, then the value of A[6] is 10.

  

  Note : for example a[1]=function () {Console.log (i)}, instead of A[1]=function{console.log (1)}, you can export the a[1] function in the console to be validated.

The Second latter (let i) concrete execution process is as follows:


var a=[];//creates an array of A;

{//Enter the first cycle
Let i=0; Note: because using let makes the For loop a block-level scope, this let i=0 in this block-level scope, not in the global environment.
A[0]=function () {
Console.log (i);
}; Note: Because of the loop,let declares I, so the entire block is a block-level scope, then a[0] This function becomes a closure.
}// statement: I use {} Here to express does not conform to the syntax, just want it to show that let exists, the FOR loop block is a block-level scope, not the global scope.

To be reasonable, This is a block-level scope, like a function scope, where the function is executed and the variables are destroyed, but because there is a closure in this block, the scope chain of the closure contains (or is referred to) a block-level scope, so before the closure is called, The variables inside this block-scoped scope are not destroyed. (More closure knowledge, you can see my post, "JavaScript closure")


{//Enter second cycle
Let I=1; Note: because let I=1; And the above let i=0; out in different scopes, so the two don't affect each other.
A[1]=function () {
Console.log (i);
}; Again, this a[i] is also a closure
}

...... Into the third cycle, at which time let i=2;
...... Enter the fourth cycle, at which time let i=3;
...... Enter the fifth cycle, at which time let i=4;
...... Enter the sixth cycle, at which time let i=5;
...... Enter the seventh cycle, at which time let i=6;
...... Enter the eighth cycle, at which time let i=7;
...... Enter the Nineth cycle, at which time let i=8;

{//Enter tenth cycle
Let i=9;
A[i]=function () {
Console.log (i);
};//also, this a[i] is also a closure
}

{
Let i=10;//does not meet the criteria and no longer executes downward. so there is no closure in this code block, let i=10, and after the end of this cycle, the bad luck is destroyed.
}

A[6] ();//Call the a[6] () function, at which point the execution environment enters the execution environment in the following code block: Funcion () {Console.log (i)};

{
Let I=6;
A[6]=function () {
Console.log (i);
}; Again, this a[i] is also a closure
}

A[6] Function (closure) in this execution environment, it will first look for the execution environment in the presence of I, not found, along the scope chain continues up to its code block execution environment, found the i=6, so output 6, that is a[6] (), the result is 6. At this point, the closure is called, so the variables I and function a[6] () in the entire code block are destroyed.

I believe that we carefully read the above function execution process, to let Var block-level scope closure has a good understanding. What I think is important is the understanding of the function execution process!

   Two. There is no variable promotion

  This is to say that using let does not exist as a variable promotion with Var. What is a variable promotion? I don't know about it before I touch es6, but I think we've all heard about function declaration Promotion: function declarations to define functions to implement function declaration promotion, so that we can call the function, then declare the function, and the function expression method does not implement the function declaration promotion, so that if the function is called First, After declaring the function, the error will be thrown!! ( for more knowledge of function declarations, see my blog, "The beauty of JavaScript functions"). and so on,var defines the variable: it can be used first, then declared, and let defines the variable: it can be declared first, then used.

  Example 3:

  

        var num1=100;        Console.log (NUM1);        Let num2=200;        Console.log (num2);        Console.log (i);         var i=10;        Console.log (j);        Let J= 5;

We can see the results as follows:

That is, the first two are declared after use, no problem. Then two are used first, after the declaration, with the Var declaration of the display undefined, and let the statement of direct error.

Description: Console.log (i);

var i=10;

is actually equivalent to:

var i;

Console.log (i);

i=10;

So there will be a undefined situation.

 

   three. Temporary Dead zone

A temporary Dead zone is a variable that will be used if one enters the current scope, but is not available and can only be obtained and used until the line of code that declares the variable appears.

Example 5:

    var tmp=123;     if (true) {        tmp= "abc";        let tmp;    }

The results are as follows:

That is: Although there is a global variable tmp in the code above, the block-level scope let declares a local variable tmp, which causes the latter to bind the block-level scope, so the TMP assignment will be an error before let declares the variable. This is the temporary Dead zone.

  

Note: ES6 specifies that temporary dead zones and non-existent variable elevation are meant to reduce runtime errors and prevent the use of this variable before the variable declaration, leading to unexpected behavior.

  Four. Duplicate declarations are not allowed

  

    function func () {let        b=100;         var b=10;    }     function Add (num) {let        num;         return num+1;    }     function another () {Let        a=10;        Let a=5;    }

The three results obtained are as follows:

Only the former two were declared for B and Num. Note: The second function, although we do not have a clear declaration, but the parameter is actually equivalent to the local variable declared with Var.

Part II: const command

What makes a const command? In fact, it is also a way of declaring constants. The const command is used to declare a constant, and once declared, its value cannot be changed . For the first time, const and let are very similar. That is, the former is used to declare a constant, which is used to declare a variable.

1.const declares a constant, which, once declared, cannot be changed.

    Const A=10;    a= 100;

The results are as follows

    

2. Since the const declaration is immutable, it must be initialized at the time of declaration.

const A;

The results are as follows:

The code block where the 3.const resides is a block-level scope, so its variables are used only in the block-level scope or in the closures within them.

    if (true) {        const a=10;    }    Console.log (a);

The results are as follows:

    

There is no variable promotion for variables declared in 4.const.

    if (true) {        console.log (a);        Const a=10;    }

The results are as follows:

  

5.const cannot declare constants repeatedly.

    var a=10;    Const a= 5;

The results are as follows:

6. TheConst command only guarantees that the address that the variable name points to is the same, and does not guarantee that the data for that address is unchanged.

  

    Const a={};    A.name= "ZZW";    Console.log (a.name);     Const b=[];    B.push ("ZZW");    Console.log (b);    Const c={};    C={name: "ZZW"};

The results are as follows:

Therefore, we use const to point to an address that is immutable, but the contents of the address can be changed.

7. If you want to freeze the object itself, you can use the Object.freeze () method.

    Const a=object.freeze ({});    A.name= "ZZW";     // undefined

So we can no longer change the properties of the object (invalid) by the Object.freeze () method.

ES6 let (understanding closures) and Const commands

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.