About closures

A closure is a function that can call a variable in the scope of another function;

Closures can only take the last value of any variable in the containing function, such as:

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
        <ul>
             <li>click me</li>
             <li>click me</li>
             <li>click me</li>
              <li>click me</li>
        </ul>
        <script type="text/javascript">
                var elements=document.getElementsByTagName('li');
                var length=elements.length;
                 for(var i=0;i<length;i++){
                         elements[i].onclick=function(){
                        alert(i);
                        }
                    }
   
    </script>
    </body>
    </html>

Because of the closure, click on each one, and the pop-up result is 4;

Closures can be forced to behave as expected by creating another anonymous function.

 1     <!DOCTYPE html>
 2     <html lang="en">
 3     <head>
 4         <meta charset="UTF-8">
 5         <title>Document</title>
 6     </head>
 7     <body>
 8         <ul>
 9              <li>click me</li>
10              <li>click me</li>
11              <li>click me</li>
12               <li>click me</li>
13         </ul>
14         <script type="text/javascript">
15                 var elements=document.getElementsByTagName('li');
16                 var length=elements.length;
17                  for(var i=0;i<length;i++){
18                          elements[i].onclick=function(num){
19                       return  function(){
20                              alert(num);
21                        }
22                            
23                         }(i)
24                     } 
25     </script>
26     </body>
27     </html>

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325629753&siteId=291194637