JavaScript全局变量和局部变量

全局变量:

  • 可以在网页的任何地方(函数内部和函数外部)使用的变量,就是“全局变量”。

  • 在函数外部定义的变量,就是“全局变量”。

  • 全局变量”既可以在函数外使用,也可以在函数内部使用。

  • “全局变量”在网页关闭时,自动消失(释放空间)。

局部变量:

  • 只能在函数内部使用的变量,称为“局部变量”。

  • “局部变量”在函数内部定义,在函数内部使用。

  • “局部变量”在函数外部无法访问。

  • “局部变量”在函数执完完毕就消失了。

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>php.cn</title>
        <script>
            //定义全局变量
            var name = "小明";
            function information(){
                //定义局部变量
                var age = 24;
               document.write("大家好,我叫"+name+",今年"+age+"岁<br/>");
            }
            //调用函数
            information();
            //下面的这行代码会报错,说age不存在
            //因为age变量是局部变量,函数执行完毕,局部变量就消失了
            //document.write("大家好,我叫"+name+",今年"+age+"岁<br/>");
        </script>
    </head>
    <body>
    </body>
</html>


Weiter lernen
||
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> <script> //定义全局变量 var name = "小明"; function information(){ //定义局部变量 var age = 24; document.write("大家好,我叫"+name+",今年"+age+"岁<br/>"); } //调用函数 information(); //下面的这行代码会报错,说age不存在 //因为age变量是局部变量,函数执行完毕,局部变量就消失了 //document.write("大家好,我叫"+name+",今年"+age+"岁<br/>"); </script> </head> <body> </body> </html>
einreichenCode zurücksetzen
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!