[JS Master's Road] ES6 series Tutorial-VAR, let, Const detailed

Source: Internet
Author: User

function show ( flag ) {             console.log ( a );             if ( flag ) {                 var a =  ' GHOSTWU ';                 return a;             } else {                 console.log ( a );                 return null;             }        } 

We lifted the variable from es5

Function show ( flag ) {             Var a;            console.log ( a );             if ( flag ) {                 a =  ' GHOSTWU ';                 return a;             } else {                 console.log ( a );                 return  null;            }         }

This mechanism, often misleading programmers in the project, even the senior front-end programmer, careless and easy to enter the pit, so ES6 introduced a block-level scope to strengthen the control of the variable life cycle.

What is a block-level scope?

1, inside the function

2, in blocks (usually refers to a pair of curly braces)

ES6 uses the new keyword let to define variables for block-level scopes, the above example, if you change to a let declaration

Function Show (flag) {Console.log (a);                if (flag) {Let A = ' GHOSTWU ';            return A;                }else {Console.log (a);            return nul; }        }

Because let is a block-level scope, there is no variable promotion like Var, so the 2nd and 7th lines are error (A is not defined)

Only if flag is true, a is defined, and the scope of access is between the braces on line 3rd and line 6th, beyond which a is not accessible, which is the block-level scope

What are the features of let?

Let cannot define two identifiers with the same name repeatedly under the same scope

Under different scopes, you can use identifiers with the same name

1 var a = ' GHOSTWU '; 2 let a = ' ghostwu2 ';
1 Let a = ' GHOSTWU ', 2 let a = ' ghostwu2 ';

In both of these ways, you will report a redefinition error (Identifier ' A ' has already been declared)

Let A = 10;            if (a) {let A = 100; Console.log (a); Console.log (a); 10


This way, there is no error, because it is two different scopes

Let's classic app

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

<script>        window.onload = function () {             var aInput =  Document.queryselectorall ("input");             for ( var i = 0; i < aInput.length; i++ ) {                ainput[i]. Onclick = function () {                     alert ( i );                 }             }        }    </script>    <input type= "button"  value= "Pushbutton 1" >&nBsp;   <input type= "button"  value= "Pushbutton 2" >    <input  Type= "button"  value= "buttons" 3 ">    <input type=" button " value=" Buttons 4 ">


If, we use the above method, each button click after the I is 4, because 4 buttons after binding the event, I the value becomes 4, the next time you click the button, all is 4, because I = 4 is shared

Usually, we will add a custom index binding to the corresponding I value on each button, and then with the This keyword, you can get it, as follows:

window.onload = function () {             var ainput = document.queryselectorall ("input");             for ( var i = 0; i  < aInput.length; i++ ) {                 aInput[i].index = i;                 ainput[i].onclick = function () {                      Alert (This.index);                 }            }         } 


Window.onload = function () {             Var ainput = document.queryselectorall ("input");             for ( var i = 0; i < ainput.length; i+ + ) {                 ainput[i].onclick =  (function ( j ) {                     return function () {                          alert ( j );                     }                 }) ( i );            }         }


window.onload = function () {             var ainput = document.queryselectorall ("input");             for ( let i = 0; i  < aInput.length; i++ ) {                 ainput[i].onclick = function () {                     alert ( i ) ;                };             }         } 

var, in the global scope, binds the property to the window, potentially creating a hidden danger of overriding the property, and the Let keyword simply obscures it and does not overwrite the property with the same name on the window


            var a = 10;         console.log ( a );  //10         console.log ( window.a ); //10         Console.log (  ' a '  in window ); //true         let user =  ' GHOSTWU ';         console.log ( user  );  //ghostwu        console.log ( window.user );  //undefined        console.log (  ' B '  in window   ); //false        /*         var RegExp =  ' GHOSTWU ';         Console.log ( RegExp );   //ghostwu        console.log ( window. regexp )  //ghostwu        console.log (  ' REGEXP '   in window ); //true        */         let RegExp =  ' GHOSTWU ';         Console.log ( RegExp );  //ghostwu         Console.log ( window. regexp );  //function regexp ()  { [native code] }         console.log (  ' RegExp '  in window );  //true

The const keyword is used to define constants, and it has the following characteristics:

. Block-level scopes

When declaring, you must give the initial value

. cannot be re-assigned

If the value is an object, then the properties inside the object are allowed to be modified.

. cannot be duplicate with other identifiers

1 Const user = ' GHOSTWU '; 2 console.log (user); 3 user = ' Zhangsan '; Error, cannot be re-assigned value


1 const user; Error, no initial value given at the time of definition

             Const user = {            name   :  ' GHOSTWU '         };         console.log ( user.name ); //ghostwu         user.name =  ' Zhangsan '; properties of   //objects allowed to be modified          console.log ( user.name );  //zhangsan 
Const USER = {name: ' Ghostwu '}; user = {//error, cannot be re-assigned to User name: ' Zhangsan '} console.log (User.Name); Error

var a = 10;2

Const A = 10; Error, redefining errors


1 Let a = 10;

2 const A = 10; Error, redefining errors


1 if (true) {

2 const A = 10;

3 Console.log (a); 10

4}

5 Console.log (a); Error: A is not defined

This article is from the "GHOSTWU" blog, make sure to keep this source http://ghostwu.blog.51cto.com/11192807/1959057

[JS Master's Road] ES6 series Tutorial-VAR, let, Const detailed

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.