初識javascript 閉包和變數提升

來源:互聯網
上載者:User

標籤:blog   inf   全域   global   closure   java   console   span   nbsp   

先上一小段代碼:

 1  function outFun(){ 2         var num = 2; 3         function inFun(){ 4             console.log(num); 5         } 6         return inFun; 7     } 8     var out = outFun(); 9     out();//2,這裡能夠訪問,其實是把num這個變數往上面一層提升了一下,out()往裡面執行了一層。剛剛好在同一層。10     console.log(num);//瀏覽器報錯,不能訪問outFun函數裡面的局部變數num

敲黑板,說概念,通俗的說:閉包就是有權訪問另外一個函數範圍變數的函數。

再說一個變數提升的概念吧;

1 var scope="global";  2 function scopeTest() { 3     console.log(scope);  4     var scope="local";  5 }  6 scopeTest(); //undefined

相當於下面的代碼:

var scope="global";  function scopeTest() {      var scope;  //但是如果沒寫var ,scope就是全域變數,不是局部變數了。    console.log(scope);      scope="local";  }  scopeTest(); //undefined

原文連結:http://www.cduyzh.com/js-closure/

 

初識javascript 閉包和變數提升

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.