JavaScript 學習筆記之變數及其範圍,javascript學習筆記

來源:互聯網
上載者:User

JavaScript 學習筆記之變數及其範圍,javascript學習筆記

一、變數

ECMAscript變數是鬆散型變數,所謂鬆散型變數,就是變數名稱可以儲存任何類型的資料,每個變數僅僅是一個用於儲存值的預留位置。

定義:var firstDemo;

二、變數的範圍

2.1基本概念

使用var 定義變數:定義該變數的範圍的局部變數,這種定義變數的方法也被成為顯式聲明。

這麼說不理解的話可以看看下面這個簡單粗暴的例子:

複製代碼 代碼如下:
test();
function test(){
var firstDemo="hello";//定義局部變數
    alert(firstDemo);//hello
}
 test();
 function test(){
    var firstDemo="hello";//定義局部變數firstDemo           
 }   
 alert(firstDemo);//報錯,firstDemo is not define

由以上兩個例子可以看出,如果在一個函數中使用var 定義一個變數,那麼該變數在函數退出後會被銷毀。

省略var 定義變數:只要調用一次定義該變數的函數,全域範圍內都可訪問該變數。這種定義變數的方法也被成為隱式聲明

複製代碼 代碼如下:
 <script type="text/javascript">
        test();
        alert(firstDemo);   //hello
        function test(){
             firstDemo="hello";           
        }       
    </script>

tips:顯式聲明的變數是在先行編譯時就已經編譯到調用對象中了,(例如var t=1;先行編譯時執行var t;解釋時執行t=1;)不同於隱式聲明變數在解釋時才被定義為全域變數。

弄清楚變數的範圍,可以協助我們思考如何合理聲明變數,這樣既減小了不必要的記憶體開銷,同時能很大程度地避免變數重複定義而覆蓋先前定義的變數所造成的麻煩。

2.2範圍分析

複製代碼 代碼如下:
<script type="text/javascript">
    function demoFunction(s){
        document.writeln(s)
    }
    var i=0; //定義全域變數
    function test(){
        demoFunction(i);
        function innerFunction(){
            var i = 1; //定義局部變數
            demoFunction(i);
        }
        innerFunction();
        demoFunction(i);
   }
   test();   
</script>

輸出結果:0 1 0

複製代碼 代碼如下:
<script type="text/javascript">
  function demoFunction(s){
    document.writeln(s)
}
  var i=0;
  function test(){
    demoFunction(i);
    function innerFunction(){
      demoFunction(i);
      var i=1;
    demoFunction(i);
    }
    innerFunction();
    demoFunction(i);
}
test();
</script>

輸出結果:

A、0 0 1 0

B、0 undefined 1 0

C、0 報錯i is not defined

各位可以猜測一下結果是哪一個,原因會在留言裡詳解。

以上就是本文的全部內容了,簡單的說任何程式語言中變數的範圍都是一個很關鍵的細節。JS中變數的範圍相對與JAVA、C這類語言顯得更自由,一個很大的特徵就是JS變數沒有塊級範圍,函數中的變數在整個函數都中有效。

聯繫我們

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