【JavaScript】變數提升以及var對變數提升的

來源:互聯網
上載者:User

標籤:lock   兩種   報錯   asc   source   java   window   javascrip   enc   

JavaScript聲明過的變數提升往往會影響到我們對變數的正常擷取,所以特寫此文,以便以後翻閱。

什麼是變數提升
//變數聲明提升function test() {    var a = "1";    var f = function(){};    var b = "2";    var c = "3";}//上述代碼等價於function test() {    var a,f,b,c;    a = "1";    f = function(){};    b = "2";    c = "3";}

js中定義變數有兩種情況:(注意在方法外不加var是不能定義變數的,出現xx is not defined)

  1. 都加var,在方法內則是局部變數,在方法外則是全域變數。
  2. 在方法內,加var為局部變數,不加var則是全域變數(在執行當前方法之後)
變數提升案例案例1

由於test1函數裡面定義了變數a,由於

var a = 'I\'m a in all'function test1 () {    console.log(a)    console.log(window.a)    var a = 'I\'m a in test1'    console.log(a)}    test1()

上述代碼相當於

var a = 'I\'m a in all'function test1 () {    var a    console.log(a) // undefined    console.log(window.a) // I'm a in all(因為window指的是全域環境)    a = 'I\'m a in test1'    console.log(a) // I'm a in test1}    test1()
案例2
var a = 'I\'m a in all'function test2 () {    console.log(a) // I'm a in all    a = 'I\'m a in test2' // 這裡本來就是賦值,所以上邊的a會輸出全域變數    console.log(a) // I'm a in test2}test2()
案例3
function test3 () {    console.log(a) // 報錯(Uncaught ReferenceError: a is not defined)    a = 'I\'m a in test3' // 這裡本來就是賦值,所以上邊的a會輸出全域變數    console.log(a) // I'm a in test3}test3()console.log(2) // I'm a in test3(本來沒有全域變數a,當test3運行時,定義了一個全域變數a,所以這裡會輸出)

【JavaScript】變數提升以及var對變數提升的

聯繫我們

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