注意未使用var的会隐身的声明为全局对象window的属性。
2.嵌套时同名的局部变量会覆盖全局的变量
<
!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<
html
>
<
head
>
<
meta
http-equiv
="content-type"
content
="text/html; charset=UTF-8"
>
<
title
>做用域的嵌套
</title>
<
script
text
="text/javascript"
>
scope="最外层";
function checkscope(){
var scope="内层";
function nested(){
var scope="最内层";
document.write(scope);
}
nested();
}
checkscope();
</script>
</head>
<
body
>
</body>
</html>
3.
<
!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<
html
>
<
head
>
<
meta
http-equiv
="content-type"
content
="text/html; charset=UTF-8"
>
<
title
>JS没有块级做用域
</title>
<
script
text
="text/javascript"
>
function test(o){
var i=0;
if(typeof o =="object"){
var j=1;
for(var k=0;k<10;k++){
document.write("k="+k+"
<
br
/>");
}
document.write("===================================
<
br
/>");
document.write("k="+k+"
<
br
/>");
}
document.write("===================================
<
br
/>");
document.write("j="+j+"
<
br
/>");
}
test({});
</script>
</head>
<
body
>
</body>
</html>
注:js的变量做用域是函数体,即便var在后面声明,可是在函数开始处也是被认为声明了的只是没有初始化而已,这个必定要和c/c++等区别。
<
!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<
html
>
<
head
>
<
meta
http-equiv
="content-type"
content
="text/html; charset=UTF-8"
>
<
title
>声明但未定义
</title>
<
script
text
="text/javascript"
>
alert(a);
var a=0;
</script>
</head>
<
body
>
</body>
</html>