Just as we can write in this form:
Copy codeThe Code is as follows:
Function Hello (){
Alert ("Hello ");
}
Hello ();
Var Hello = function (){
Alert ("Hello ");
}
Hello ();
They are all the same.
However, when we modify the functions, we will find a strange problem.
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function Hello (){
Alert ("Hello ");
}
Hello ();
Function Hello (){
Alert ("Hello World ");
}
Hello ();
</Script>
We can see this result: two consecutive Hello World messages are output. Instead of Hello and Hello World.
This is because Javascript is not fully interpreted and executed in order, but a "pre-compilation" of Javascript will be performed before the interpretation. During the pre-compilation process, the defined function is preferentially executed, and all var variables are created. The default value is undefined to improve the program execution efficiency. That is to say, the above Code is actually precompiled by the JS engine into this form:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var Hello = function (){
Alert ("Hello ");
}
Hello = function (){
Alert ("Hello World ");
}
Hello ();
Hello ();
</Script>
We can clearly see from the code above that the function is actually data and a variable. We can also assign values to the function ). Of course, to prevent such a situation, we can also do the following:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function Hello (){
Alert ("Hello ");
}
Hello ();
</Script>
<Script type = "text/javascript">
Function Hello (){
Alert ("Hello World ");
}
Hello ();
</Script>
In this way, the program is divided into two sections, and the JS engine will not put them together.