本文實例講述了javascript中的閉包概念與用法。分享給大家供大家參考,具體如下:
閉包的概念:閉包是指有權訪問另一個函數作用域中的變量的函數 (引自《javascript高級程序設計第三版》178頁)。閉包的優點是不會產生全局變量,避免變量污染問題,但是閉包也有一個缺點就是閉包攜帶包含它的函數作用域會比其它函數占用更多的內存,過度使用會導致內存占用過多。
wiki上關于閉包的概念:
In programming languages, closures (also lexical closures or function closures) are techniques for implementing lexically scoped name binding in languages with first-class functions. Operationally, a closure is a record storing a function[a] together with an environment:[1] a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created.[b] A closure—unlike a plain function—allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope.
簡單來說:閉包是一個存儲了函數以及與這個函數相關的環境信息的記錄。
閉包實踐一:初次體驗閉包
function a() { var temp = 100; function b() { console.log(++temp); } return b;}var fn = a(); // 此時fn屬于全局的函數。fn();// 101fn();// 102在函數a的內部return出了一個局部函數b。讓函數fn接收函數a的返回值,也就是函數b。連續執行了兩次fn,輸出結果101,,102表示,函數fn一直引用著函數a中的局部變量temp。每次調用fn,temp都會被自增1。從此處說明了函數a一直沒有被垃圾回收機制(GC)回收。以上代碼還可以這樣優化:
function a() { var temp = 100; return function() { console.log(++temp); }}var fn = a();a = null;fn();// 101fn();// 102fn = null; // 調用完畢后要,要解除對內部匿名函數的引用,以便釋放內存閉包實踐二:閉包與變量
分析下面的代碼
html結構:
<ul> <li>0</li> <li>1</li> <li>2</li></ul>
javascript結構:
var ul = document.querySelector('ul');// 為了演示方便,直接用html5的apivar lis = ul.children;for(var i=0; i< lis.length; i++) { lis[i].οnclick=function(){ console.log(i); }}當點擊每個li時,輸出的全都是3,在點擊事件之前,for循環早已經執行完了,i的值為3。為了防止這種情況發生,for循環還可以修改成這樣:
for(var i=0; i< lis.length; i++) { lis[i].οnclick=function(num){ return function(){ console.log(num); } }(i)}
新聞熱點
疑難解答
圖片精選