JS作用域、立即執(zhí)行函數(shù)、閉包

2018-4-25    seo達(dá)人

如果您想訂閱本博客內(nèi)容,每天自動(dòng)發(fā)到您的郵箱中, 請點(diǎn)這里

作用域    

首先先介紹一下作用域等一些基礎(chǔ)概念。

 每個(gè)JavaScript函數(shù)都是一個(gè)對象,對象中有些屬性我們可以訪問,但有些不可以,這些屬性僅供JavaScript引擎存取,[[scope]]就是其中一個(gè)。

[[scope]] : 指的就是我們所說的作用域,其中存儲(chǔ)了執(zhí)行期上下文的集合

作用域鏈 : [[scope]] 中所存儲(chǔ)的執(zhí)行期上下文對象的集合,這個(gè)集合呈鏈?zhǔn)芥溄?,我們把這種鏈接叫做作用域鏈。

運(yùn)行期上下文  : 當(dāng)函數(shù)執(zhí)行時(shí),會(huì)創(chuàng)建一個(gè)稱為執(zhí)行期上下文的內(nèi)部對象(AO)。一個(gè)執(zhí)行期上下文定義了一個(gè)函數(shù)執(zhí)行的環(huán)境,函數(shù)每次執(zhí)行時(shí)對應(yīng)的執(zhí)行環(huán)境都是的,所以多次調(diào)用一個(gè)函數(shù)會(huì)導(dǎo)致創(chuàng)建多個(gè)執(zhí)行上下文,當(dāng)函數(shù)執(zhí)行完畢,它所產(chǎn)生的執(zhí)行上下文被銷毀。

查找變量  :從作用域鏈的頂端依次向下查找。

下面舉一些例子:

[html] view plain copy
  1. function a(){  
  2.     function b(){  
  3.         function c(){  
  4.   
  5.         }  
  6.         c();  
  7.     }  
  8.     b();  
  9. }  
  10. a();  
  11.   
  12.   
  13. a defined a.[[scope]] ----> 0 : GO          //a定義的時(shí)候產(chǎn)生GO對象  
  14. a doing   a.[[scope]] ----> 0 : aAO           //a執(zhí)行的時(shí)候新產(chǎn)生AO對象  
  15.                             1 : GO  
  16.   
  17. b defined  b.[[scope]] ----> 0 : aAO            //子級b定義會(huì)繼承父級a運(yùn)行時(shí)產(chǎn)生的對象  
  18.                              1 : GO   
  19. b doing    b.[[scope]] ---->  0 : bAO            //子級b新產(chǎn)生AO對象  
  20.                               1 : aAO   
  21.                               2 : GO   
  22.                                 
  23. c defined  c.[[scope]] ---->  0 : bAO            //c定義時(shí)會(huì)繼承b運(yùn)行時(shí)產(chǎn)生的屬性  
  24.                               1 : aAO   
  25.                               2 : GO                          
  26. c doing     c.[[scope]] ----> 0 : cAO            //c執(zhí)行時(shí)同時(shí)又產(chǎn)生新的AO  
  27.                               1 ;bAO   
  28.                               2 : aAO   
  29.                               3 : GO   

立即執(zhí)行函數(shù)

之前學(xué)過函數(shù)的定義、函數(shù)表達(dá)式,還有一種函數(shù)叫做立即執(zhí)行函數(shù)。

立即執(zhí)行函數(shù):函數(shù)執(zhí)行過后立即被銷毀。

立即執(zhí)行函數(shù)的官方寫法:

[html] view plain copy
  1. // 立即執(zhí)行函數(shù)的官方寫法  
  2. (function() {} ());  W3C建議此種  
  3. (function() {})();  

針對初始化功能的函數(shù),可以有參數(shù)。

[html] view plain copy
  1. var num = function (a,b){  
  2.     return a + b;  
  3. }(1,2);  
  4.   
  5. (function abc(){  
  6.     var a = 123;  
  7.     var b = 234;  
  8.     console.log(a+b);  
  9. }())  

只有表達(dá)式才能被執(zhí)行符號執(zhí)行,能被執(zhí)行符號執(zhí)行的表達(dá)式,函數(shù)名字會(huì)被自動(dòng)忽略。

[html] view plain copy
  1. function test(){  
  2.     console.log("a");  
  3. }()    會(huì)出現(xiàn)語法解析錯(cuò)誤,因?yàn)槔ㄌ柷懊媸呛瘮?shù)聲明  
  4.   
  5. (+ function test( ){  
  6.     console.log('a');  
  7. }())                    -------->打印出a  

下面是一道曾阿里面試題

[html] view plain copy
  1. function test(a, b, c, d){  
  2.     console.log(a + b + c + d);  
  3. }(1, 2, 3, 4);  
  4.   
  5. // 不報(bào)錯(cuò)也沒有執(zhí)行        

下面是幾道經(jīng)典的例題,可以參考一下:

[html] view plain copy
  1.   
[html] view plain copy
  1. function test(){  
  2.     var arr = [];  
  3.     for(var i = 0; i < 10; i ++){  
  4.         arr[i] = function (){  
  5.             console.log(i);  
  6.         }  
  7.     }  
  8.     return arr;  
  9. }  
  10. var myArr = test();  
  11. for(var j = 0; j < 10; j++){  
  12.     myArr[j]();  
  13. }    
[html] view plain copy
  1.   
[html] view plain copy
  1. // 輸出:10個(gè)10  

那么采用立即執(zhí)行函數(shù)呢?會(huì)有怎樣的結(jié)果呢?

[html] view plain copy
  1. function test(){  
  2.     var arr = [];  
  3.     for(var i = 0; i < 10; i ++){  
  4.         (function(j){  
  5.             arr[i] = function (){  
  6.             console.log(j + " ");  
  7.         }  
  8.         }(i))  
  9.     }  
  10.     return arr;  
  11. }  
  12. var myArr = test();  
  13. for(var j = 0; j < 10; j++){  
  14.     myArr[j]();  
  15. }   
[html] view plain copy
  1.   
[html] view plain copy
  1. // 輸出結(jié)果  0 1 2 3 4 5 6 7 8 9   

大家可以自行思考一下。

閉包

閉包的現(xiàn)象:當(dāng)內(nèi)部函數(shù)保存到外部時(shí)會(huì)產(chǎn)生閉包。


閉包會(huì)導(dǎo)致原有的作用域鏈不釋放,造成內(nèi)存泄漏

(內(nèi)存泄漏:內(nèi)存占用(比如:手握沙子,握得越緊手里剩得就越少))


閉包觸發(fā)的情況:

    兩個(gè)或多個(gè)函數(shù)互相嵌套,把里面的函數(shù)保存到外部,這樣的情況一定會(huì)產(chǎn)生閉包。從外面還可以調(diào)用里面的函數(shù)。


閉包的作用:

            實(shí)現(xiàn)公有變量

                    eg:函數(shù)累加器

            可以做緩存(存儲(chǔ)結(jié)構(gòu))

                    eg:eater

               可以實(shí)現(xiàn)封裝,屬性私有化

                    eg:person()

                模塊化開發(fā),防止污染全局變量



[html] view plain copy
  1. // 函數(shù)累加器  
  2. function add(){  
  3.     var count = 0;  
  4.     function demo(){  
  5.         count ++;  
  6.         console.log(count);  
  7.     }  
  8.     return demo;  
  9. }  
  10. var counter = add();  
  11. counter();  
  12. counter();  
  13. counter();  
  14. counter();  
  15. counter();  
  16. counter();  
  17.   
  18.   
  19. // eater  
  20. function test(){  
  21.     var food = "apple";  
  22.     var obj = {  
  23.         eatFood : function (){  
  24.             if(food != ""){  
  25.                 console.log("I am eating  " + food);  
  26.                 food = "";  
  27.             }  
  28.             else{  
  29.                 console.log("There is nothing!");  
  30.             }  
  31.         },  
  32.         pushFood : function (myFood){  
  33.             food = myFood;  
  34.         }  
  35.     }  
  36.     return obj;  
  37. }  
  38. var person = test();  
  39. person.eatFood();  
  40. person.eatFood();  
  41. person.pushFood('banana');  
  42. person.eatFood();  

附加一個(gè)逗號操作符:

        先看前面的表達(dá)式,再看后面的表達(dá)式,把后面表達(dá)式的計(jì)算結(jié)構(gòu)返回

例題:

[html] view plain copy
  1. var f =(  
  2.     function f(){  
  3.         return "1";  
  4.     },  
  5.     function g(){  
  6.         return 2;  
  7.     }  
  8. )();  
  9. console.log(typeof(f));   
  10.   
  11. // -------number  
  12.   
  13. var x = 1;  
  14. if(function f(){}){  
  15.     x += typeof f;  
  16. }  
  17. console.log(x);  
  18. // --------> 1undefined  
  19. 藍(lán)藍(lán)設(shè)計(jì)sillybuy.com )是一家專注而深入的界面設(shè)計(jì)公司,為期望卓越的國內(nèi)外企業(yè)提供卓越的UI界面設(shè)計(jì)、BS界面設(shè)計(jì) 、 cs界面設(shè)計(jì) 、 ipad界面設(shè)計(jì) 、 包裝設(shè)計(jì) 、 圖標(biāo)定制 、 用戶體驗(yàn) 、交互設(shè)計(jì)、 網(wǎng)站建設(shè) 、平面設(shè)計(jì)服務(wù)

分享本文至:

日歷

鏈接

個(gè)人資料

存檔