问题描述
我已经读过一个好的做法是放置一个var语句,它定义了每个函数顶部的所有局部变量。下面的代码说明了为什么这是一个好主意,因为显然使用变量后 em 未定义。
I've read that a good practice is to put a var statement which defines all local variables at the top of each function. The following code shows why this is a good idea, since apparently a var after a variable is used makes it undefined.
但是有人可以告诉我为什么这种情况?
But can someone tell me why this is the case?
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var a=1;
function foo() {
//a = 2; //outputs 2,2 because this overwrites the external variable value
//var a = 2; //outputs 2,1 because the "var" keyword creates a second variable with local scope which doesn't affect the external variable
console.log(a);
var a = 3; //ouputs "undefined,1" ???
}
foo();
console.log(a);
};
</script>
</head>
<body>
</body>
</html>
推荐答案
function foo() {
console.log(a);
var a = 3;
}
相当于
function foo() {
var a;
console.log(a);
a = 3;
}
因为在JavaScript变量声明被悬挂但是初始值设定项不是。
because in JavaScript variable declarations are hoisted but initializers are not.
您可以通过以下示例看到这是真的:
You can see that this is literally true with the following example:
e = 0;
function foo() {
e = 1;
try {
throw 2;
} catch (e) {
var e = 3;
alert("In catch " + e);
}
alert("Before end of function " + e);
}
foo();
alert("Outside function " + e);
提醒
因为变量声明已被提升,因此函数外部的 e
不会被 e = 1
更改,但 e = 3
发生在 catch
内,所以 3
不会影响函数末尾的 e
,而不是覆盖异常值。
because the variable declaration is hoisted so the e
outside the function is not changed by e = 1
, but the e = 3
occurs inside the catch
so the 3
does not affect the e
at the end of the function, instead over-writing the exception value.
这篇关于当var出现之后,为什么函数变量未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!