關於Javascript閉包的理解(二)

來源:互聯網
上載者:User

先看看閉包的科學的定義:閉包是可以包含自由(未綁定)變數的代碼塊;這些變數不是在這個代碼塊或者任何全域上下文中定義的,而是在定義代碼塊的環境中定義。“閉包” 一詞來源於以下兩者的結合:要執行的代碼塊(由於自由變數的存在,相關變數引用沒有釋放)和為自由變數提供綁定的計算環境(範圍)。

聽上去有點暈,我說說我的理解。閉包是一個受到了保護的變數空間,由內嵌函數產生。用到閉包通常是為瞭解決變數的範圍問題。我舉兩個使用閉包的例子,也許看例子比什麼都明白。

例子1:迴圈對多個按鈕綁定click事件。

不用閉包的情況:

  1. <html>
  2. <head>
  3. <script type="text/javascript">
  4. function OnLoad()
  5. {
  6.     var arr = document.getElementsByTagName("input");
  7.     for(var i=0;i<arr.length;i++)
  8.     {
  9.         arr[i].onclick=function(){
  10.             alert(i);
  11.         }
  12.     }
  13. }
  14. </script>
  15. </head>
  16. <body onload="OnLoad()">
  17. <input type="button" name="button" value="button1" />
  18. <input type="button" name="button" value="button2" />
  19. <input type="button" name="button" value="button3" />
  20. <input type="button" name="button" value="button4" />
  21. <input type="button" name="button" value="button5" />
  22. <input type="button" name="button" value="button6" />
  23. <input type="button" name="button" value="button7" />
  24. </body>
  25. </html>

猛點這裡測試結果,你發現不管點哪個按鈕,都會彈出7。原因是當你點擊buttun時,迴圈已經執行完畢,這時候i就等於7.

再看看使用閉包的情況

  1. <html>
  2. <head>
  3. <script type="text/javascript">
  4. function OnLoad()
  5. {
  6.     var arr = document.getElementsByTagName("input");
  7.     for(var i=0;i<arr.length;i++)
  8.     {
  9.         arr[i].onclick=closureTest(i);
  10.     }
  11. }
  12. function closureTest(i)
  13. {
  14.     return function(){
  15.         alert(i);
  16.     }
  17. }
  18. </script>
  19. </head>
  20. <body onload="OnLoad()">
  21. <input type="button" name="button" value="button1" />
  22. <input type="button" name="button" value="button2" />
  23. <input type="button" name="button" value="button3" />
  24. <input type="button" name="button" value="button4" />
  25. <input type="button" name="button" value="button5" />
  26. <input type="button" name="button" value="button6" />
  27. <input type="button" name="button" value="button7" />
  28. </body>
  29. </html>

猛點這裡測試結果,你發現會像你想象的那樣,button按鈕一次會彈出0、1、2、3、4、5、6。這就是典型的利用閉包來影響變數的範圍的樣本。當然,閉包能做很多不同的事情,但究其原理,還是通過影響變數的範圍來實現的。

 

轉載:http://www.playgoogle.com/post/66.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.