简体   繁体   English

函数中未定义的变量

[英]Undefined variable within a function

Look at the following snippet: 请看以下代码段:

var fruit = "Orange";
echoThis();

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

When I run this snippet, the alert of fruit is undefined . 当我运行这个片段时, fruit的警报是undefined Why? 为什么?

First I thought it has something to do with hoisting, that within a funciton, the JS engine "lifts" all var declarations to the top or something, but then I would expect the alert to display Apple , not undefined . 首先我认为它与吊装有关,在一个函数中,JS引擎将所有var声明“提升”到顶部或者其他东西,但是我希望警报显示Apple ,而不是undefined

There's probably some elementary JS behaviour I'm unaware of. 可能有一些基本的JS行为我不知道。 Anyone care to explain? 有人在乎解释吗?

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

It's because of hoisting . 这是因为吊装 Variables declared in a function are available for the entire scope, but they are assigned a value where you put it. 函数中声明的变量可用于整个范围,但会为它们分配一个值。

This: 这个:

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

becomes this: 成为这个:

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

This is why you code is evaluated successfully, but fruit's value is undefined. 这就是您成功评估代码的原因,但未定义水果的值。

also: 也:

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. 
}

if you really want to change this then remove the var in the function. 如果你真的想改变它,那么删除函数中的var

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

The variable is hoisted to the top of the function when it is compiled. 编译时,变量被提升到函数的顶部。

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

Translates to this

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

So when the alert is called it is technically undefined at this point. 因此,当调用警报时,此时技术上尚未定义。 To stop seeing that move your variable declaration before the alert statement. 要停止在alert语句之前看到移动变量声明。

that's because js has lexical scope and hoisting. 那是因为js有词法范围和悬挂。

so echoThis looks for fruit within itself before looking outside and since you have var fruit = "Apple"; 所以echoThis在寻找外面之前寻找fruit ,因为你有var fruit = "Apple"; , fruit is hoisted in echoThis . fruitechoThis悬挂。

Besides the above responses, if you want to get the orange AND the apple after.. you could try to pass the variable simply as a parameter and work in the function 除了上面的回答,如果你想获得橙色和苹果之后..你可以尝试将变量简单地作为参数传递并在函数中工作

 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