Home >Web Front-end >JS Tutorial >How to set global variables in javascript
The method of setting global variables in javascript is: 1. Define the variable outside the function of js; 2. Define the variable directly without using var, and implicitly declare the global variable; 3. Use "window. variable" Name" is defined as a global variable.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Three methods
1. Define a variable outside the js function
var name='测试'; function XX(){ alert(name); }
2. Do not use var, directly define the variable, and implicitly declare the global variable
name='测试'; function XX(){ alert(name); }
In this method, even if the variable is within a function, it becomes a global variable after the function is executed----but it will not be known to other functions until the function is executed, so in the end It is best to define it outside the function
3. Use window. variable name to define it as a global variable, but note: it is recommended to write window. variable name when calling, of course you can not write it; we commonly use document.getXXX document The object is the window's
window.name='测试'; function XX(){ alert(window.name); }
Advantages of global variables:
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.
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to set global variables in javascript. For more information, please follow other related articles on the PHP Chinese website!