In JavaScript, variables have the same scopes as those in other programming languages: local variables and global variables.
The following example shows the relationship between local variables and global variables:
Instance 1:
VaR MSG = "global variable"; function show () {MSG = "local variable"; document. writeln (MSG) ;}show (); document. writeln (MSG );
The final execution result is:
Local variable
Local variable
Example 2:
VaR MSG = "global variable"; function show () {var MSG; MSG = "local variable"; document. writeln (MSG);} Show (); document. writeln (MSG );
The final execution result is:
Local variable
Global Variables
Analysis: it is not difficult to understand that calling the show () function will print "local variables". The show () function in the instance operates on the global variable MSG, when show () at the end of the function, the local variable MSG has been changed to another value, so the "local variable" is printed, and the show () A new local variable MSG is defined in the function, and its local variable is also operated (the global variable MSG is overwritten). When the show () function ends, the remaining Code does not have a half-cent relationship with the show () function, so the "global variable" is printed ".