很淺的關于閉包的了解,還有很長的路要走,上次去百度面試,當我寫出這代碼的時候,面試官說這就是他當時到雅虎面試時候面試官給他的題o(╯□╰)o,直接貼代碼吧
<html>
<head>
.test {
width:100px;
height:100px;
border:red 1px solid;
}
</head>
<body>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
</body>
</html>
<script type="text/javascript">
var k = document.getElementsByTagName("div");
for(var i = 0; i < k.length; i ++) {
(function(i){
k[i].onclick = function() {
alert(i);
}
})(i)
}
</script>
匿名函數将目前I的值傳入進去,形成閉包,将i的值保留在記憶體中,當單擊每個div時候,就會彈出相應的index也就是i的值,如果不加這個立即執行的匿名函數,那麼,當單擊事件出發時候,得到的,永遠是循環不成立的時候的i的值,也就是4.