for 循环里面事件函数的i值

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript">
    window.onload=function(){
        var aP=document.getElementsByTagName("p");
        for(var i=0; i<aP.length; i++){
            aP[i].onclick=function(){
                console.log(i);//i=4
                /*我的理解:
                    预解析:aP=undefined; i=undefined
                    执行:aP=document.getElementsByTagName("p")
                        第一次遇到表达式i=0,赋值;判断i<aP.length;执行块里面的function,里面没有i往上级找,此时i=0,应该i=0。。。
                        第一次遇到表达式i=0,赋值;判断i<aP.length;并没有去执行块里面的function,当click的时候才去执行,
                *       否则,如果立即执行,点击的时候就失效了,当点击的时候,此时循环已经执行完了。往上一级找的时候,此时i=aP.length;
                *
                * */
            }
            a(i); //这种是立即执行的,所以查找的时候i是当前的值;
            function a(a){
                alert(a);
            }
        }
    }

    </script>
</head>
<body>
 <p>1</p>
 <p>2</p>
 <p>3</p>
 <p>4</p>
</body>
</html>
原文地址:https://www.cnblogs.com/zifeiyu/p/3430977.html