[英]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";
, fruit
在echoThis
悬挂。
除了上面的回答,如果你想获得橙色和苹果之后..你可以尝试将变量简单地作为参数传递并在函数中工作
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.