ghostsk 2012-05-28
JavaScript作用域之没有块级作用域
与C、C++以及JAVA不同,Javscript没有块级作用域。函数中声明的所有变量,无论是在哪里声明的,在整个函数中它们都是有定义的。
上例子
例子一、下面代码中,变量i、j和k和作用域是相同的,它们三个在整个函数中都有定义。
<script>
function test(o){
var i=0;
if(typeof o == "object"){
var j=0;
for(var k=0; k<10; k++){
document.writeln("k="+k);
}
document.writeln("k2="+k);
}
document.writeln("j="+j);
}
test(new String("pppp"));
</script>输出结果为:k=0k=1k=2k=3k=4k=5k=6k=7k=8k=9+++k=10j=0
这一规则可以产生惊人的结果,上代码
<script>
var scope="global";
function f(){
alert(scope);
var scope="local";
alert(scope);
}
f();
</script>结果:第一个alert输出:underfined而不是global,第二个alert输出local
上面函数f与下面的函数等价:
function f(){
var scope;
alert(scope);
var scope="local";
alert(scope);
}如果你写成:
<script>
var scope="global";
function f(){
alert(scope);
var scope2="local";
alert(scope2);
}
f();
</script> 输出结果为:第一个alert为global,第二个为:local.