【发布时间】:2012-05-31 14:24:11
【问题描述】:
我读过一个很好的做法是在每个函数的顶部放置一个定义所有局部变量的 var 语句。下面的代码说明了为什么这是一个好主意,因为显然 var after 使用了一个变量使其未定义。
但是谁能告诉我为什么会这样?
<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>
【问题讨论】:
标签: javascript var