JavaScript閉包

 Normally, when the function terminates, the scope is released because it's no longer necessary. However, in the case of an inner function that's returned to the outer application and assigned to an external variable, the scope of the inner function is attached to the outer function, which in turn is attached to the calling application—just enough to maintain the integrity of the inner function and the outer function argument and variable. Returning a function literal created as an internal object within another function, and assigning it to a variable in the calling application, is known as closure in JavaScript. This concept of scope chaining ensures that the data necessary for the application to work is in place.

通常,當函數結束時其作用範圍也就會釋放,因爲已經不再需要了。但是,當一個內部函數向一個外部應用程序返回一個值,並賦給一個外部變量時,內部函數的作用範圍就將附加到外部函數上,然後在附加到調用它們的應用程序中,這樣才能保證內部函數和外部函數和變量的完整性。返回一個在其他函數中以內部對象形式創建的函數字面量,然後將其賦值給調用它的應用程序中的一個變量,這就是JavaScript中的閉包。它將引入一個作用範圍鏈的概念,它是確保應用程序在此時能夠正常工作所需要的數據。

以上內容摘自Learning JavaScript,太難理解了。下面是對“閉包”通俗點的定義。

概念

1. 閉包就是能夠讀取其他函數內部變量的函數。本質上,閉包就是將函數內部和函數外部連接起來的一座橋樑。

2. 當內部函數在定義它的作用域的外部引用時,就創建了該內部函數的閉包,如果內部函數引用了位於外部函數的變量,當外部函數調用完畢後,這些變量在內存不會被釋放,因爲閉包需要它們。

閉包的用途

最大用處有兩個,一是讀取函數內部的變量,二是讓這些變量的值始終保持在內存中。

注意:

1.由於閉包會使得函數中的變量都被保存在內存中,內存消耗很大,所以不能濫用閉包,否則會造成網頁性能的問題,在IE中可能導致內存泄露。解決方法是,在退出函數之前,將不使用的局部變量刪除。

2.閉包會在父函數外部改變父函數內部變量的值。所以,如果你把父函數當作對象(Object)使用,把閉包當作它的公用方法(Public Method),把內部變量當作它的私有屬性(Private value),這時一定要小心,不要隨便改變父函數內部變量的值。

例1:

  1. <script type="text/javascript"
  2. function outerFunc(base){ 
  3.     var punc = "!"
  4.  
  5.     //返回內部函數 
  6.     return function(ext){ 
  7.         return base + ext + punc; 
  8.     } 
  9. function processNested(){ 
  10.     //創建對內部函數的訪問 
  11.     var baseString = outerFunc("Hello "); 
  12.  
  13.     document.writeln(baseString+"<br />"); 
  14.     document.writeln(baseString()+"<br />"); 
  15.  
  16.     //內部函數仍然將訪問外部函數的參數 
  17.     var newString = baseString("World"); 
  18.     document.writeln("newString= "+newString+"<br />"); 
  19.  
  20.     //再次調用 
  21.     var notherString = baseString("Reader"); 
  22.     document.writeln("notherString= "+notherString+"<br />"); 
  23.  
  24.     //創建另一個內部函數實例 
  25.     var anotherBase = outerFunc("Hiya, Hey "); 
  26.  
  27.     //另一個本地字符串 
  28.     var lastString = anotherBase("you"); 
  29.     document.writeln("lastString= "+lastString); 
  30. window.onload = processNested; 
  31. </script> 

 顯示爲:

 解釋: 

baseString、notherString爲外部函數outerFunc()的內部函數的一個引用, 

“Hello”、“Hiya,Hey”傳遞給外部函數的參數base, 

“word”、“you”傳遞給內部函數的參數ext 

例2:

  1. function outerFun() 
  2. var a=0; 
  3. function innerFun() 
  4. a++; 
  5. alert(a); 
  6. return innerFun; //注意這裏 
  7. var obj=outerFun(); 
  8. obj(); //結果爲1 
  9. obj(); //結果爲2 
  10. var obj2=outerFun(); 
  11. obj2(); //結果爲1 
  12. obj2(); //結果爲2 

本文首發地址:http://www.boyige.tk/blog/?p=366

參考:http://www.jb51.net/article/24101.htm

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章