以前看zakas的Professional JavaScript,讀過閉包的章節,當時以爲理論上是理解了,把書上的案例都實踐了一遍。但例子是純粹控制檯調試實現的,印象不深入,今天練習原生javascript的時候碰上閉包,簡單梳理一下。javascript
先看實例的DEMO:css
http://cssplusplus.com/demo/js/1_1_DivControl%20.html html
實現代碼:java
<!DOCTYPE html> <html> <head> <style> #outer { width: 500px; margin: 0 auto; padding: 0px; text-align: center; } #changBox { width: 100px; height: 100px; background: black; margin: 10px auto; display: block; } </style> <script> function changeStyle(elem, attr, value) { elem.style[attr] = value; } window.onload = function() { var Attr = ["width", "height", "background", "display", "display"]; var Val = ["200px", "200px", "red", "none", "block"]; var oBtn = document.getElementsByTagName("input"); var oDiv = document.getElementById("changBox"); for (i = 0; i < oBtn.length; i++) { oBtn[i].index = i; oBtn[i].onclick = function() { (this.index == oBtn.length - 1) && (oDiv.style.cssText = ""); changeStyle(oDiv, Attr[this.index], Val[this.index]); } } }; </script> </head> <body> <div id="outer"> <input type="button" value="變寬"> <input type="button" value="變高"> <input type="button" value="變色"> <input type="button" value="隱藏"> <input type="button" value="重置"> <div id="changBox"></div> </div> </body> </html>
若是咱們把33行的:
changeStyle(oDiv, Attr[this.index], Val[this.index]);
改爲:
changeStyle(oDiv, Attr[i], Val[i]);
結果如何?
這是修改後的DEMO:閉包
http://cssplusplus.com/demo/js/1_1_DivControlWrong.html 函數
點擊上面的button是沒有任何反應的。this
問題出如今閉包上,問題分析以下:調試