關於js範圍

來源:互聯網
上載者:User

關於js範圍
我們知道在程式設計語言中,範圍的作用就是控制變數、參數的可見範圍和生命週期。 js中提供了函數範圍的功效,比如在函數中定義的變數外部是無法訪問到的: function jsFunc(){       var a = 5;  }alert(a); // undefined但是js中卻沒有提供塊範圍的功效,比如我們在java代碼中如果些如下代碼: 複製代碼    public static Boolean b = false;    public static void main(String[] args) {        if(!b){            int a = 5;        }        System.out.println(a); // 這裡會報編譯時間錯誤    }    複製代碼在列印輸出a的時候,會報變數未定義異常。 而在js中寫如下代碼: 複製代碼var flg = false;function jsFunc(){  alert(a); // undefined    if(!flg){        var a = 5;    }    alert(a); // 5}jsFunc();alert(a); // Uncaught ReferenceError: a is not defined複製代碼在它會彈出5,說明在函數內部區塊層級元素內部單獨定義的變數,在整個函數範圍內是可以訪問到的。 因此這就需要我們在命名變數時額外注意,避免出現參數沖的問題。

聯繫我們

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