Javascript閉包示範

來源:互聯網
上載者:User
有個網友問了個問題,如下的html,為什麼點擊所有的段落p輸出都是5,而不是alert出對應的0,1,2,3,4。

<!DOCTYPE HTML><html><head><meta charset="utf-8" /><title>閉包示範</title><style type="text/css">p {background:gold;}</style><script type="text/javascript"> 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> 


以上情境是初學者經常碰到的。即擷取HTML元素集合,迴圈給元素添加事件。在事件響應函數中(event handler)擷取對應的索引。但每次擷取的都是最後一次迴圈的索引。

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

瞭解了原因,摸索出了很多解決辦法(純粹是興趣)。最先想到的前兩種

1、將變數 i 儲存給在每個段落對象(p)上

function init1() {  var pAry = document.getElementsByTagName("p");   for( var i=0; i<pAry.length; i++ ) {     pAry[i].i = i;     pAry[i].onclick = function() {        alert(this.i);      }  }}

2、將變數 i 儲存在匿名函數自身

function init2() {  var pAry = document.getElementsByTagName("p");   for( var i=0; i<pAry.length; i++ ) {   (pAry[i].onclick = function() {        alert(arguments.callee.i);    }).i = i;  }}

後又想到了三種

3、加一層閉包,i 以函數參數形式傳遞給內層函數

function init3() {  var pAry = document.getElementsByTagName("p");  for( var i=0; i<pAry.length; i++ ) {   (function(arg){       pAry[i].onclick = function() {          alert(arg);       };   })(i);//調用時參數   }}

4、加一層閉包,i 以局部變數形式傳遞給內層函數

function init4() {  var pAry = document.getElementsByTagName("p");  for( var i=0; i<pAry.length; i++ ) {     (function () {      var temp = i;//調用時局部變數       pAry[i].onclick = function() {        alert(temp);      }    })();  }}

5、加一層閉包,返回一個函數作為響應事件(注意與3的細微區別)

function init5() {  var pAry = document.getElementsByTagName("p");  for( var i=0; i<pAry.length; i++ ) {   pAry[i].onclick = function(arg) {       return function() {//返回一個函數        alert(arg);     }   }(i);  }}

後又發現了兩種

6、用Function實現,實際上每產生一個函數執行個體就會產生一個閉包

function init6() {    var pAry = document.getElementsByTagName("p");    for( var i=0; i<pAry.length; i++ ) {      pAry[i].onclick = new Function("alert(" + i + ");");//new一次就產生一個函數執行個體    }}

7、用Function實現,注意與6的區別

function init7() {    var pAry = document.getElementsByTagName("p");    for( var i=0; i<pAry.length; i++ ) {         pAry[i].onclick = Function('alert('+i+')');    }}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.