variables scope confusion in javascript
This question already has an answer here:
There are only two kinds of scope in Javascript; function scope and global scope.
The code inside the if
statement doesn't have a scope of its own, so the variable inside the if
statement is the same one as the one outside it.
Declaring a variable more than once in a scope doesn't create more than one variable. The var
keyword inside the if
statement is ignored as the variable already is declared once in the scope, so it's just an assignment.
Note also that the declaration of variables is hoisted to the top of the scope, so even if a declaration is inside a code block that is not executed, the variable is still created:
var foo = 1; // a global variable
(function() {
console.log(foo) //outputs "undefined"
foo = 2; // sets the local variable
if(false) {
var foo = 3; // creates the local variable, but the assignment never happens
}
console.log(foo) //outputs 2
})();
console.log(foo) //outputs 1
if
does not introduce a scope block (I understand it does in some langauges). In JavaScript, only function() {}
creates a scope block.
上一篇: 未捕获的ReferenceError:lat未定义
下一篇: 变量范围混淆在JavaScript中