前端面試題——js閉包

來源:互聯網
上載者:User

什麼是閉包?以下代碼點擊<p> 會輸出什麼?為什麼?能大概說明白的話繼續問能想出幾種解決辦法。

==========

出錯:擷取HTML元素集合,迴圈給元素添加事件。在事件響應函數中(event handler)擷取對應的索引。但每次擷取的都是最後一次迴圈的索引。 

出錯原因:初學者並未理解JavaScript的閉包特性。通過element.onclick=function(){alert(i);}方式給元素添加點擊事件。響應函數function(){alert(i);}中的 i 並非每次迴圈時對應的 i(如0,1,2,3,4)而是迴圈後最後 i 的值5。 或者說迴圈時響應函數內並未能儲存對應的值 i,而是最後一次i++的值5。 

解決方案:見html代碼注釋部分


<!DOCTYPE HTML> <html> <head> <meta charset="utf-8" /> <title>閉包示範</title> <style type="text/css">     p {background:gold;}  </style> <script type="text/javascript">   /* 網上的七種方法//將變數 i 儲存給在每個段落對象上function init() {          var pAry = document.getElementsByTagName("p");          for( var i=0; i<pAry.length; i++ ) {       pAry[i].i=i;             pAry[i].onclick = function() {               alert(this.i);          }     }  }//將變數i儲存在匿名函數自身function init(){var pAry=document.getElementsByTagName("p");for (var i = 0; i <pAry.length; i++) {(pAry[i].onclick=function(){alert(arguments.callee.i)}).i=i;};}  //加一層閉包,i以函數參數形式傳遞給內層函數function init(){var pAry=document.getElementsByTagName("p");for (var i = 0; i < pAry.length; i++) {(function(arg){pAry[i].onclick=function(){alert(arg);};})(i);//調用時參數};}//加一層閉包,i 以局部變數形式傳遞給內層函數 function init(){var pAry=document.getElementsByTagName("p");for (var i = 0; i < pAry.length; i++) {(function(){var temp=i;//調用時局部變數pAry[i].onclick=function(){alert(temp);}})();};}//加一層閉包,返回一個函數作為響應事件function init(){var pAry=document.getElementsByTagName("p");for (var i = 0; i < pAry.length; i++) {pAry[i].onclick=function(arg){return function(){alert(arg);}}(i);};}function init(){var pAry=document.getElementsByTagName("p");for (var i = 0; i < pAry.length; i++) {pAry[i].onclick=new Function("alert("+i+");");//new一次就產生一個函數執行個體};}function init(){var pAry=document.getElementsByTagName("p");for (var i = 0; i < pAry.length; i++) {pAry[i].onclick=Function("alert("+i+");");};}*/function init() { var pAry = document.getElementsByTagName("p"); for( var i=0; i<pAry.length; i++ ) { pAry[i].onclick = function() { alert(i); } } } </script>   </head>   <body onload="init();">   <p>產品 0</p>   <p>產品 1</p>   <p>產品 2</p>   <p>產品 3</p>   <p>產品 4</p>   </body>   </html> 


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.