注意未使用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>