先看看閉包的科學的定義:閉包是可以包含自由(未綁定)變數的代碼塊;這些變數不是在這個代碼塊或者任何全域上下文中定義的,而是在定義代碼塊的環境中定義。“閉包” 一詞來源於以下兩者的結合:要執行的代碼塊(由於自由變數的存在,相關變數引用沒有釋放)和為自由變數提供綁定的計算環境(範圍)。
聽上去有點暈,我說說我的理解。閉包是一個受到了保護的變數空間,由內嵌函數產生。用到閉包通常是為瞭解決變數的範圍問題。我舉兩個使用閉包的例子,也許看例子比什麼都明白。
例子1:迴圈對多個按鈕綁定click事件。
不用閉包的情況:
- <html>
- <head>
- <script type="text/javascript">
- function OnLoad()
- {
- var arr = document.getElementsByTagName("input");
- for(var i=0;i<arr.length;i++)
- {
- arr[i].onclick=function(){
- alert(i);
- }
- }
- }
- </script>
- </head>
- <body onload="OnLoad()">
- <input type="button" name="button" value="button1" />
- <input type="button" name="button" value="button2" />
- <input type="button" name="button" value="button3" />
- <input type="button" name="button" value="button4" />
- <input type="button" name="button" value="button5" />
- <input type="button" name="button" value="button6" />
- <input type="button" name="button" value="button7" />
- </body>
- </html>
猛點這裡測試結果,你發現不管點哪個按鈕,都會彈出7。原因是當你點擊buttun時,迴圈已經執行完畢,這時候i就等於7.
再看看使用閉包的情況
- <html>
- <head>
- <script type="text/javascript">
- function OnLoad()
- {
- var arr = document.getElementsByTagName("input");
- for(var i=0;i<arr.length;i++)
- {
- arr[i].onclick=closureTest(i);
- }
- }
- function closureTest(i)
- {
- return function(){
- alert(i);
- }
- }
- </script>
- </head>
- <body onload="OnLoad()">
- <input type="button" name="button" value="button1" />
- <input type="button" name="button" value="button2" />
- <input type="button" name="button" value="button3" />
- <input type="button" name="button" value="button4" />
- <input type="button" name="button" value="button5" />
- <input type="button" name="button" value="button6" />
- <input type="button" name="button" value="button7" />
- </body>
- </html>
猛點這裡測試結果,你發現會像你想象的那樣,button按鈕一次會彈出0、1、2、3、4、5、6。這就是典型的利用閉包來影響變數的範圍的樣本。當然,閉包能做很多不同的事情,但究其原理,還是通過影響變數的範圍來實現的。
轉載:http://www.playgoogle.com/post/66.html