<!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>