• 【javascript】变量作用范围


    一、全局变量&局部变量


    test=""  全局变量

    var test=""  局部变量,无块的概念,作用域为function 或者script块

    二、有意思的特例


    1.因为没有块的概念,会出现奇怪的结果

    <script>
        var scope = "globale";
        function test()
        {
            alert(scope);//打印undefined。因为scope在test函数被重新定义覆盖,即使执行这条语句之前并未重新赋值全局变量。
    var scope = "local";
    alert(scope); //打印local
    }
    test();


    </script>

    效果等同于

    <script>
        var scope = "global";
        function test()
        {
            var scope;
            alert(scope); 
            var scope = "local";
            alert(scope); 
        }
        test();
    </script>

     2. 例子

    <script type="text/javascript">
    alert('kuai1:'+i);
    function test(){
        var j = 2;
        alert('test:'+i+','+j);
        i = 5;
    }
    </script>
    <script type="text/javascript">
    var i = 1;
    alert('kuai2:'+i);
    function test1(){
        alert('test1:'+i+','+j);
    }
    test();
    test1();

    //执行顺序 alert('kuai1:'+i); Error,因为i在第一个script块中未定义 //alert('kuai2:'+i); 弹窗kuai2:1 因为i在第二个script块中定义
    //test() 弹窗test:1,2   如果function test()里面的i=5修改为var i=5就会弹窗出test:undefined,2
    //test1() Error,因为j未定义
    </script>
    
    
    计划、执行、每天高效的活着学着
  • 相关阅读:
    Trie树
    递归函数两种方式的区别
    揭开HTTPS的神秘面纱
    补码到底是个什么东西
    浮点数的运算精度丢失
    PHP的stdClass
    2019-10-24
    MySQL存储引擎
    代码整洁之道小结
    NFS4 挂载同主机多个目录
  • 原文地址:https://www.cnblogs.com/huxiaoyun90/p/4142710.html
Copyright © 2020-2023  润新知