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>
”
本文深入探讨了JavaScript中变量作用域的概念,对比了与C等其他语言的差异,并强调了在函数中声明变量的最佳实践。通过具体示例展示了在函数内部声明的变量如何在不同上下文中被访问,以及在不同作用域内使用变量的重要性。
228

被折叠的 条评论
为什么被折叠?



