Declared global variables in JS are mainly divided into explicit declaration or implicit declaration.
Method 1:
Using var (keyword) + variable name (identifier) is declared outside the function, that is, global variables. Otherwise, local variables are declared in the function. The explicit statement is as follows:
Var test = 5; // global variable function a () {var cc = 3; // local variable alert (test);} function B () {alert (test );}
Method 2:
If var is not used, assign a value to the identifier test, which implicitly declares the global variable test. Even if the statement is in a function, after the function is executed, test becomes a global variable.
Test = 5; // global variable function a () {aa = 3; // global variable alert (test );}
Method 3:
The window global object is used for declaration. The Global object attributes correspond to global variables as follows:
window.test;window.test = 5;
This method is often used to expose some functions to the global environment after an anonymous function is executed. For example, the last sentence in JQuery1.5
window.jQuery = window.$ = jQuery;
Advantages of global variables:
It can reduce the number of variables and reduce the time consumption caused by data transmission of actual and formal parameters.
Disadvantages of global variables:
(1) The global variables are stored in the static storage area. When the program starts running, the memory is allocated. When the program ends, the memory is released. Compared with Dynamic Allocation and release of local variables, the survival time is relatively long, so too many global variables will occupy a large amount of memory units.
(2) global variables damage the function encapsulation performance. A function is like a black box. It is generally input and output through function parameters and return values, and is relatively independent within the function. However, if a global variable is used in a function, the statements in the function body can bypass function parameters and return values for access. This damages the independence of the function and enables the function to depend on global variables. At the same time, it also reduces the portability of the function.
(3) global variables reduce the readability of the function code. Because multiple functions may use global variables, the value of global variables may change at any time during function execution, which is very unfavorable for program troubleshooting and debugging.
Therefore, we recommend that you do not use global variables.
Three typesDifferencesSee http://www.cnblogs.com/snandy/archive/2011/03/19/1988284.html for details