变量的作用域

安稳与你 提交于 2019-11-28 21:50:54

1、局部变量和全局变量

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title>Java Script</title>
        <script type="text/javascript">
            var welcome = function() {
                var String1="我是局部变量";
                console.log(String2);
            }
        </script>
    </head>

    <body bgcolor="aquamarine">
        <script>
        var String2="我是全局变量";
        welcome();
        </script>

    </body>

</html>

可以通过局部访问全局变量,但是不能在函数的外面访问局部变量。是局部变量还是全局变量关键是看var的位置。

例如:

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title>Java Script</title>
        <script type="text/javascript">
        function welcome(){
            num1=2;
            console.log(num1);
        }
        </script>
    </head>

    <body bgcolor="aquamarine">
        <script>
        
            var num1 = 1;
            welcome();
            console.log(num1);
        </script>

    </body>

</html>

返回的结果都是2,他们都是在对全局变量进行操作。

2、变量的声明提前

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title>Java Script</title>
        <script type="text/javascript">
        
        </script>
    </head>

    <body bgcolor="aquamarine">
        <script>
            console.log(num1);
            var num1 = 1;
            console.log(num1);
        </script>

    </body>

</html>

在程序中第一次输出num1之前,num1还未被声明过,如果按java和c的语法,这样是会报错的,但是javascript在执行时遵循声明提前方式,实际上是这样执行的:

var num1;     console.log(num1);
num1 = 1;
console.log(num1);

即:把声明放在作用域的最前面。

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!