<!DOCTYPE HTML><HTML><HeadLang= "en"> <MetaCharSet= "Utf-8"/> <title></title> <Scriptsrc=".. /js/jquery-1.10.2.js "></Script> <Script>//1 I output global variables for global variables functionMyName () {i= 'Global Variables'; } myName (); functionSayname () {alert (i); } sayname ();//2 I run error for local variable display i undefined functionMyName () {varI='Local Variables'; } myName (); functionSayname () {alert (i); } sayname ();//3 Remove the MyName () in 1 to run error display i is undefined, although the function is declared, but there is no calling function, the assignment of I in the function is invalidated. functionMyName () {i= 'Global Variables'; } functionSayname () {alert (i); } sayname ();//4 Put the MyName () in 1 under Sayname () to run the error display I is undefined, although the function called the function is declared but because the function called by JavaScript runs from top to bottom,//myname () is not running when Sayname is running. functionMyName () {i= 'Global Variables'; } functionSayname () {alert (i); } sayname (); MyName (); //5 The running result is a global variable. Although the variable name is the same, but one is a global variable, one is a local variable, there is an essential difference, local variables can only be used within this function varI= 'Global Variables'; functionMyName () {varI= 'Local Variables'; } myName (); functionSayname () {alert (i); } sayname (); //6 Change the local variable of 5 to a global variable, and the running result shows the changed global variable varI= 'Global Variables'; functionMyName () {i= 'changing the global variables'; } myName (); functionSayname () {alert (i); } sayname (); //7 The running result shows undefined, because the code executes in order from top to bottom, before the output I and only I, not to I initialization. vari; functionSayname () {alert (i); I= 'Global Variables'; } sayname ();//8 Run results show global variables, initialize I before output no problem vari; functionSayname () {alert (i); I= 'Global Variables'; } sayname ();//9 The running result shows undefined because the output is a local variable, and the local variable is initialized after the output. varI= 'Global Variables'; functionSayname () {alert (i); varI= 'Local Variables'; } sayname (); </Script></Head><Body></Body></HTML>
Summarize the differences between global and local variables in JavaScript and the difference between declaring and calling functions