0141 Scope of variables: global variables, local variables, v

In JavaScript, according to the scope of the different variables can be divided into two types:

  • Global Variables
  • Local variables

2.1 Global Variables

在全局作用域下声明的变量叫做全局变量(在函数外部定义的变量)。
  • Global variables can be used anywhere in the code
  • Variables in the global scope under var statement is a global variable
  • Under special circumstances, do not use the variables declared within the function var is a global variable (not recommended) [In the global scope, without the use of a variable is declared global variables var. ]

2.2 Local variables

在局部作用域下声明的变量叫做局部变量(在函数内部定义的变量)
  • Local variables can only be used inside the function
  • Var variable functions inside the local variable declarations
  • The function parameter is actually local variables

2.3 the difference between the global and local variables

  • Global variables: can be used in any one place, will only be destroyed when the browser is closed, so the comparison of total memory
  • Local variables: internal functions use only when they are in the code block is executed, it will be initialized; run when the code block, will be destroyed, thus saving memory space and more
        var num = 10; // num就是一个全局变量
        console.log(num);

        function fn() {
            console.log(num);
        }
        fn();

        // console.log(aru); // 报错

        // 局部变量:在局部作用域下的变量,或者在函数内部的变量就是 局部变量
        // 注意: 函数的形参也可以看做是局部变量
        function fun(aru) {
            var num1 = 10; // num1就是局部变量 只能在函数内部使用
            num2 = 20;
        }
        fun();
        // console.log(num1); // 报错
        // console.log(num2);

Guess you like

Origin www.cnblogs.com/jianjie/p/12151845.html