js變量中的細節問題

 
 
<!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>全局變量-養成使用var聲明變量的好習慣</title>
    <script text="text/javascript">
        scope="global";
        function checkscope(){
            scope="local";//實際上修改的是全局的變量
            document.write(scope);
            myscope="local";//實際上建立一個全局的變量
            document.write(myscope);
        }
        checkscope();
    </script>
    </head>
    <body>

    </body>
</html>
 
注意未使用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>
相關文章
相關標籤/搜索