[js master road] var, let, const

 1         function show( flag ){
 2             console.log( a );
 3             if( flag ){
 4                 var a = 'ghostwu';
 5                 return a;
 6             } else {
 7                 console.log( a );
 8                 return null;
 9             }
10         }    

Let's start with the elevation of variables in es5. Because of the elevation of variables, the program mentioned above can access the value of a in lines 2 and 7. It's just undefined. If you are not familiar with the pre-interpretation mechanism of variables such as javascript, you may think that lines 2 and 7 will report errors. Only when flag is true, variable a will be declared. In fact, JavaScript interprets lexically. The above code will be interpreted as follows:

 1        function show( flag ){
 2             var a;
 3             console.log( a );
 4             if( flag ){
 5                 a = 'ghostwu';
 6                 return a;
 7             } else {
 8                 console.log( a );
 9                 return null;
10             }
11         }        

This mechanism often misleads programmers in projects, even senior front-end programmers, who are easy to get into the pit carelessly, so ES6 introduces block-level scope to strengthen the control of variable life cycle.

What is a block scope?

1. Function interior

2. In a block (usually between a pair of curly braces)

In es6, a new keyword let is used to define variables, which are block-level scopes, as in the previous example, if changed to let declaration

 1     function show( flag ){
 2             console.log( a );
 3             if( flag ){
 4                 let a = 'ghostwu';
 5                 return a;
 6             }else {
 7                 console.log( a );
 8                 return nul;
 9             }
10         }

Since let is a block-level scope and does not generate variable escalation like var, lines 2 and 7 are not defined at this time.

Only if flag is true, a will be defined, and the access scope will be between the braces in line 3 and line 6, beyond which a will not be accessed, which is the block scope.

What are the features of let?

In the same scope, let cannot redefine two identical identifiers

In different scopes, identical identifiers can be used

1 var a = 'ghostwu';
2 let a = 'ghostwu2';
1 let a = 'ghostwu';
2 let a = 'ghostwu2';

In both cases, Identifier'a'has already been declared

1         let a = 10;
2         if( a ){
3             let a = 100;
4             console.log( a ); //100
5         }
6         console.log( a ); //10    

In this way, no error will be reported, because there are two different scopes.

let's classical application

In four buttons, get the index of the currently clicked button

 1      <script>
 2         window.onload = function(){
 3             var aInput = document.querySelectorAll("input");
 4             for( var i = 0; i < aInput.length; i++ ){
 5                 aInput[i].onclick = function(){
 6                     alert( i );
 7                 }
 8             }
 9         }
10     </script>
11 
12    <input type="button" value="Button 1">
13     <input type="button" value="Button 2">
14     <input type="button" value="Button 3">
15     <input type="button" value="Button 4">

If we use the above method, i is 4 after each button is clicked, because the value of i becomes 4 after the event is bound by four buttons. Next time we click on the button, all of them are 4, because i = 4 is shared.

Usually, we will add a custom index to each button to bind the corresponding i value, and then with the help of this keyword, we can do as we wish, as follows:

1         window.onload = function(){
2             var aInput = document.querySelectorAll("input");
3             for( var i = 0; i < aInput.length; i++ ){
4                 aInput[i].index = i;
5                 aInput[i].onclick = function(){
6                     alert(this.index);
7                 }
8             }
9         }

Another way is to borrow the form of immediate expression + closure, as follows:

 1         window.onload = function(){
 2             var aInput = document.querySelectorAll("input");
 3             for( var i = 0; i < aInput.length; i++ ){
 4                 aInput[i].onclick = (function( j ){
 5                     return function(){
 6                         alert( j );
 7                     }
 8                 })( i );
 9             }
10         }    

By using let keyword and using the characteristics of block-level scope, we can easily achieve our goal.

1         window.onload = function(){
2             var aInput = document.querySelectorAll("input");
3             for( let i = 0; i < aInput.length; i++ ){
4                 aInput[i].onclick = function(){
5                     alert( i );
6                 };
7             }
8         }

 

In the global scope, var binds attributes to windows, which may result in the hidden danger of overwriting attributes. The let keyword only covers it and does not cover the same name attributes on windows.

 1         var a = 10;
 2         console.log( a );  //10
 3         console.log( window.a ); //10
 4         console.log( 'a' in window ); //true
 5 
 6         let user = 'ghostwu';
 7         console.log( user ); //ghostwu
 8         console.log( window.user ); //undefined
 9         console.log( 'b' in window  ); //false
10 
11 
12         /*
13         var RegExp = 'ghostwu';
14         console.log( RegExp );  //ghostwu
15         console.log( window.RegExp ); //ghostwu
16         console.log( 'RegExp' in window ); //true
17         */
18 
19         let RegExp = 'ghostwu';
20         console.log( RegExp );  //ghostwu
21         console.log( window.RegExp ); //function RegExp() { [native code] }
22         console.log( 'RegExp' in window ); //true    

The const keyword is used to define constants. It has the following characteristics:

Block-level scopes

When declaring, you must assign an initial value

Can't be reassigned

If the value is an object, then the attributes in the object are allowed to be modified.

Can't rename with other identifiers

1         const user = 'ghostwu';
2         console.log( user );
3         user = 'zhangsan'; //Report errors, Can't reassign
1 const user; //Error, defined without initial value
1         const user = {
2             name  : 'ghostwu'
3         };
4         console.log( user.name ); //ghostwu
5         user.name = 'zhangsan';  //Object properties are allowed to be modified
6         console.log( user.name ); //zhangsan
1        const user = {
2             name  : 'ghostwu'
3         };
4         user = {    //Errors can't be repaid user assignment
5             name : 'zhangsan'
6         }
7         console.log( user.name ); //Report errors
1         var a = 10;
2         const a = 10; // Reporting and redefining errors
1         let a = 10;
2         const a = 10; //Reporting and redefining errors
1        if ( true ) {
2             const a = 10;
3             console.log( a ); //10
4         }
5         console.log( a ); //Report errors:a is not defined

Keywords: Javascript Windows

Added by eppievojt on Sat, 08 Jun 2019 04:40:09 +0300