ES6 new attribute let (upgraded version of var) instead of function closure to solve the problem

Understand the difference between ES6's let attribute and var

The difference between let's introduction and var

1. Var has no block-level scope, but let has a block-level scope
. 2. In js, only function has its own independent scope.
If you don’t understand:
For example:

{
    
    var a=10}
console.log(a);

1. When the webpage is running, a can be printed directly
2. If var is replaced by let

{
    
    let a=10}
console.log(a);

Insert picture description here

1. The console shows that a is not defined.
2. This shows that let has its own independent scope.
3. Since there is an independent scope, let can replace the function to solve the function closure problem.

For example:
we use a for loop to bind the listener events for 5 buttons. Click each button to print the corresponding number.

<body>
 <button>1</button>
 <button>2</button>
 <button>3</button>
 <button>4</button>
 <button>5</button>
</body>
<script>
    var btn=document.getElementsByTagName("button");//获取所有button的一个列表
    for(var i=0;i<btn.length;i++){
    
    
        btn[i].onclick=function(){
    
    console.log(i+1);}
    }    


1. In this way, we will only print the last number 5 no matter which console is clicked.
2. The previous 1234 is overwritten, and the button will print 5.
3. It means that the {} of for has no block-level scope. of

The previous solution (function closure)

 for(var i=0;i<btn.length;i++){
    
    
     (function a(i){
    
    
            btn[i].onclick=function(){
    
    console.log(i+1);} 
	 })(i);   
    }    

**
Closure it with an immediate function, and then pass in the value of i. (not recommend)

The current solution (ES6 let: an upgraded version of var)

Replace var directly with let

   for(let i=0;i<btn.length;i++){
    
    
            btn[i].onclick=function(){
    
    console.log(i+1);} 
    }    

Solve the problem directly, simple and convenient (recommended!!!)

Now students who are learning js can develop let related writing, it is also a perfect version of var! ! ! ! !

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_42232622/article/details/110825448