javascript 變數的作用範圍

來源:互聯網
上載者:User

from:http://hanxin830311.javaeye.com/blog/181127

1。根據作用範圍不同,變數有全域變數和局部變數兩種。在函數裡定義的變數為局部變數,局部變數只在函數內有效。 如果局部變數和全域變數用相同的變數名,則局部變數將覆蓋全域變數

<script>       //定義全域變數test       var test = "全域變數";        function checkscope(  )       {           var test = "局部變數";           alert(test);       }       checkscope(  );    //在函數裡定義的變數為局部變數,局部變數只在函數內有效。   //如果局部變數和全域變數用相同的變數名,則局部變數將覆蓋全域變數   </script>  

 

2。JavaScript語言沒有區塊範圍。

<script>       function test(o)           {           //定義變數i,變數i的作用範圍是整個函數               var i = 0;           if (typeof o == "object")            {               //定義變數j,變數j的作用範圍是整個函數內,而不是if塊內。                   var j = 5;                   for(var k = 0; k < 10; k++)                   {                   //k的作用範圍是整個函數內,而不是迴圈體內                       document.write(k);                   }           }              //即使出了迴圈體,k的值依然存在           alert(k + "\n" + j);        }       test(document);   </script>  

因為JavaScript語言沒有區塊範圍,有時會出現一些非常奇怪的結果:

<script>var scope = "全域變數";function test(){alert(scope); var scope = "局部變數";alert(scope); }test();//代碼第一次輸出的scope值並不是"全域變數",而是undefined。知識這是因為scope在test函數中已經被重新定義了,局部變數在test函數中將全域有效,即在scope還沒定義之前全域變數scope依然被覆蓋。</script>

變數作用範圍在進行HTML事件處理時一樣有效:

<script type="text/javascript">  var x = "全域變數";</script><form action="#" method="get"><input type="button" value="局部變數"   onclick="var x = '局部變數'; alert('輸出x局部變數的值:' + x);" /><input type="button" value="全域變數 "   onclick="alert('輸出x全域變數的值: ' + x);" /></form>
相關文章

聯繫我們

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