Reference function call js file

One problem encountered in the development, code demo as follows:

test.js contents of the file:

 1 var b = getHomeCity(); 

 

Test.html contents of the file:

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <title>Test HTML Page</title>
 5         <script type="text/javascript" src="test.js"></script>
 6         <script type="text/javascript">
 7 
 8             (
 9                 function(window){
10                     alert(b);
11                 }
12             )(window);
13             
14             function getHomeCity(){
15                 return 10;
16             }
17         </script>
18 is      </ head>
 . 19      <body>
 20 is          <-! Here was put into a ->
 21 is      </ body>
 22 is </ HTML>

Run Results:

Open the console found error:

getHomeCity () undefined:

 

 

Later I changed a bit getHomeCity () function of the position:

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <title>Test HTML Page</title>
 5         <script type="text/javascript">
 6             function getHomeCity(){
 7                 return 10;
 8             }
 9         </script>
10         <script type="text/javascript" src="test.js"></script>
11         <script type="text/javascript">
12 
13             (
14                 function(window){
15                     alert(b);
16                 }
. 17              ) (window);
 18 is              
. 19          </ Script>
 20 is      </ head>
 21 is      <body>
 22 is          <-! Here was put into a ->
 23 is      </ body>
 24 </ HTML>

operation result:

 

Script code blocks in the same function call:

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <title>Test HTML Page</title>
 5         <script type="text/javascript">
 6             
 7             var b = getHomeCity();
 8             (
 9                 function(window){
10                 
11                     alert(b);
12                 }
13             )(window);
14             function getHomeCity(){
15                 return 10;
16             }
17         </script>
18     </ head>
 . 19      <body>
 20 is          <-! here was put into a ->
 21 is      </ body>
 22 is </ HTML>

operation result:

 

 

in conclusion:

Script code in the same block, the function can call each other, according to the principle of lifting function definition, function definition EDITORIAL or later can execute the function

But calling functions between different Script code blocks, be sure to define the function before calling function, otherwise the situation will appear undefined.

 

Guess you like

Origin www.cnblogs.com/lanshanxiao/p/11862875.html