簡體   English   中英

函數中未定義的變量

[英]Undefined variable within a function

請看以下代碼段:

var fruit = "Orange";
echoThis();

function echoThis() {    
    alert(fruit);
    var fruit = "Apple";
}

當我運行這個片段時, fruit的警報是undefined 為什么?

首先我認為它與吊裝有關,在一個函數中,JS引擎將所有var聲明“提升”到頂部或者其他東西,但是我希望警報顯示Apple ,而不是undefined

可能有一些基本的JS行為我不知道。 有人在乎解釋嗎?

JS小提琴: https//jsfiddle.net/z37230c9/

這是因為吊裝 函數中聲明的變量可用於整個范圍,但會為它們分配一個值。

這個:

function echoThis() {    
    alert(fruit);
    var fruit = "Apple";
}

成為這個:

function echoThis() {    
   var fruit;
   alert(fruit);
   fruit = "Apple";
}

這就是您成功評估代碼的原因,但未定義水果的值。

也:

var fruit = "Orange"; //this fruit variable
echoThis();

function echoThis() {    
    alert(fruit);
    var fruit = "Apple"; // is overridden by this, 
     //because it's re-declared in a local scope. 
}

如果你真的想改變它,那么刪除函數中的var

   function echoThis() {    
        alert(fruit);
        fruit = "Apple";  //this now accesses the global fruit.
    }

編譯時,變量被提升到函數的頂部。

function echoThis() {    
    alert(fruit);
    var fruit = "Apple";
}

Translates to this

function echoThis() {    
    var fruit;
    alert(fruit);
    fruit = "Apple";
}

因此,當調用警報時,此時技術上尚未定義。 要停止在alert語句之前看到移動變量聲明。

那是因為js有詞法范圍和懸掛。

所以echoThis在尋找外面之前尋找fruit ,因為你有var fruit = "Apple"; fruitechoThis懸掛。

除了上面的回答,如果你想獲得橙色和蘋果之后..你可以嘗試將變量簡單地作為參數傳遞並在函數中工作

 var fruit = "Orange"; echoThis(fruit); function echoThis(fruit) { alert(fruit); // You will get the orange var fruit = "Apple"; alert(fruit); // You will get the apple } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM