Declaring global variables in JS is mainly divided into explicit declaration or implicit declaration, which are introduced below.
Declaration method one:
Use var (keyword) variable name (identifier) to declare it outside the function, which is a global variable, otherwise it is a local variable declared in the function. This method is an explicit declaration. The details are as follows:
Instead of using var, directly assign a value to the identifier test, which will implicitly declare the global variable test. Even if the statement is within a function, test becomes a global variable when the function is executed.
Use the window global object to declare. The properties of the global object are also global variables. The details are as follows:
It can reduce the number of variables and reduce the time consumption caused by data transfer of actual parameters and formal parameters.
Disadvantages of global variables:
(1) Global variables are stored in static storage areas. Memory is allocated for them when the program starts running, and the memory is released when the program ends. Compared with the dynamic allocation and dynamic release of local variables, the lifetime is relatively long, so too many global variables will occupy more memory units.
(2) Global variables destroy the encapsulation performance of functions. A function is like a black box, which generally performs input and output through function parameters and return values. The internal implementation of the function is relatively independent. However, if global variables are used in the function, then the statements in the function body can bypass the function parameters and return values for access. This situation destroys the independence of the function and makes the function dependent on global variables. At the same time, it also reduces the portability of this function.
(3) Global variables make the code of the function less readable. Since multiple functions may use global variables, the value of the global variable may change at any time when the function is executed, which is very detrimental to program error checking and debugging.
Therefore, it is best not to use global variables unless it is absolutely necessary.