前端开发javascript— 作用域

js开发前端|前端开发流行的js|前端开发js兼容性问题
<script type=”text/javascript”>
    var a = “hello”;
    b = “world”;
    Test();
    function Test() {
        alert(a + ” ” + b);
        var a = “welcome”;
        b = “china”;
        alert(a + ” ” + b);
    }
    alert(a + ” ” + b);
</script>
<script type=”text/javascript”>
    alert(a);
    alert(b);
    var a = “111”;
    b = “111”;
</script>
当我们执行运行这段脚本时,可以发现,首先弹出undefined,然后回提示脚本错误,提示b不存在。由此就可以表明,a在预编译的过程中就已经被创建并且初始化为undefined,而b却只能在实际运行时按顺序去解释。其实在预编译后的Javascript代码可以近乎理解如下:
<script type=”text/javascript”>
    var a = undefined;
    alert(a);
    alert(b);
    a = “111”;
    b = “111”;
</script>
function Test() { var a = undefined; alert(a + ” ” + b); var a = “welcome”; b = “china”; alert(a + ” ” + b); }
<script type=”text/javascript”>
    var a = “hello”;
    b = “world”;
    Test();
    function Test() {
        alert(a + ” ” + b);
        a = “welcome”;
        b = “china”;
        alert(a + ” ” + b);
    }
    alert(a + ” ” + b);
</script>
<script type=”text/javascript”>
    var a = “hello”;
    b = “world”;
    Test();
    function Test() {
        alert(a + ” ” + b);
        var a = “welcome”;
        var b = “china”;
        alert(a + ” ” + b);
    }
    alert(a + ” ” + b);
</script>
<script type=”text/javascript”>
    a = “hello”;
    b = “world”;
    Test();
    function Test() {
        alert(a + ” ” + b);
        var a = “welcome”;
        b = “china”;
        alert(a + ” ” + b);
    }
    alert(a + ” ” + b);
</script>
应该是undefined world,welcome china,hello china.
web前端开发 java ui|关于java前端\/后端开发|前端开发 js填充数据
» 本文来自:前端开发者 » 《前端开发javascript— 作用域》
» 本文链接地址:https://www.rokub.com/3883.html
» 您也可以订阅本站:https://www.rokub.com
赞(0)
64K

评论 抢沙发

评论前必须登录!