JavaScript's Syntax comes from C, In all other C-like languages, a block(a set of statements wrapped in curly braces) creates a scope.
Variables declared in a block are not visible outside of the block. JavaScript uses the block syntax, but does not provide block scope: a variable
declared in a block is visible everywhere in the function containing the block. This can be surprising to programmers with experience in other
languages.
In most languages, it is generally best to declare variables at the site of first use. That turns out to be a bad practice in JavaScript because
it does not have block scope. It's better to declare all variables at the top of each function.
</pre><pre name="code" class="javascript"><script>
var testFunc = function(o) {
var i = 4;
document.writeln('<br/>value of g= ' + g);
//document.writeln('<br/>value of j= ' + j);
if (typeof o === 'string') {
var k;
for (k = 0; k < i; k++) {
var g = k + i;
}
}
document.writeln('<br/>value of i= ' + i);
document.writeln('<br/>value of k= ' + k);
document.writeln('<br/>value of g= ' + g);
}
testFunc('hello, world');
</script>
输出结果:
value of g= undefined
value of i= 4
value of k= 4
value of g= 7
变量 g定义在在 for 循环块里,而k 定义在if块中,在C和Java看来,再for,if块外是不能再引用g和k的,而JavaScript则可以,因为他没block scope的概念,只要在
function里定义了,就可以在任何地方引用。这里,当还没有定义变量g时,确使用了 它“
document.writeln('<br/>value of g= ' + g);结果为 undefined,这是因为,当函数开始时会扫描整个function block, 为里面的每一个变量赋予初始值undefined.
而"<span style="font-family: Arial, Helvetica, sans-serif;">//document.writeln('<br/>value of j= ' + j);"则会编译失败,因为j was not defined anywhere.</span>
”