原生javascript學習:javascript閉包執行個體

來源:互聯網
上載者:User

之前看zakas的Professional JavaScript,讀過閉包的章節,當時覺得理論上是理解了,把書上的案例都實踐了一遍。但例子是純粹控制台調試實現的,印象不深刻,今天練習原生javascript的時候碰上閉包,簡單梳理一下。
先看執行個體的DEMO:
http://cssplusplus.com/demo/js/1_1_DivControl%20.html
實現代碼:
01 <!DOCTYPE html>
02 <html>
03 <head>
04 <style>
05 #outer {
06     width: 500px;
07     margin: 0 auto;
08     padding: 0px;
09     text-align: center;
10 }
11 #changBox {
12     width: 100px;
13     height: 100px;
14     background: black;
15     margin: 10px auto;
16     display: block;
17 }
18 </style>
19 <script>
20 function changeStyle(elem, attr, value) {
21     elem.style[attr] = value;
22 }
23 window.onload = function() {
24     var Attr = ["width", "height", "background", "display", "display"];
25     var Val = ["200px", "200px", "red", "none", "block"];
26     var oBtn = document.getElementsByTagName("input");
27     var oDiv = document.getElementById("changBox");
28         
29     for (i = 0; i < oBtn.length; i++) {
30         oBtn[i].index = i;
31         oBtn[i].onclick = function() {
32             (this.index == oBtn.length - 1) && (oDiv.style.cssText = "");
33             changeStyle(oDiv, Attr[this.index], Val[this.index]);
34         }
35     }
36 };
37 </script>
38 </head>
39 <body>
40 <div id="outer">
41 <input type="button" value="變寬">
42 <input type="button" value="變高">
43 <input type="button" value="變色">
44 <input type="button" value="隱藏">
45 <input type="button" value="重設">
46 <div id="changBox"></div>
47 </div>
48 </body>
49 </html>
如果我們把33行的:
1 changeStyle(oDiv, Attr[this.index], Val[this.index]);
改成:
1 changeStyle(oDiv, Attr[i], Val[i]);www.2cto.com
結果如何?
這是修改後的DEMO:
http://cssplusplus.com/demo/js/1_1_DivControlWrong.html
點擊上面的button是沒有任何反應的。
問題出現在閉包上,問題分析如下:
1. 我給每個button的onclick動作都綁定了一個function
2. 我點擊button,就要調用這個function
3. 這個function執行到changeSytle,開始尋找參數
4. 參數中有變數 i, i 是多少?
5. 先從當前的匿名函數的範圍找 i,沒有找到
6. 接著到window.onload 綁定的匿名函數去找(注意javascript裡面沒有塊級範圍概念),找到 i
7. i 是多少? i = oBtn.length,因為 window.onload 綁定的匿名函數返回後, 變數 i 的值是 oBtn.length
8. 這正是onclick綁定的匿名函數的範圍鏈中儲存的 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.