Just as we can write in this form:
Copy Code code as follows:
function Hello () {
Alert ("Hello");
}
Hello ();
var Hello = function () {
Alert ("Hello");
}
Hello ();
are actually the same.
But when we make changes to the functions in them, we find the strange problem.
Copy Code code as follows:
<script type= "Text/javascript" >
function Hello () {
Alert ("Hello");
}
Hello ();
function Hello () {
Alert ("Hello World");
}
Hello ();
</script>
We'll see the result: two consecutive times Hello world. Rather than the Hello and hello world we imagined.
This is because JavaScript does not fully interpret the execution in sequence, but rather to "precompile" the JavaScript before it is interpreted, and in the process of precompilation, the defined function is executed first, and all VAR variables are created with the default value of undefined. To improve the efficiency of program execution. That is to say, a piece of code is actually precompiled by JS engine to this form:
Copy Code code as follows:
<script type= "Text/javascript" >
var Hello = function () {
Alert ("Hello");
}
Hello = function () {
Alert ("Hello World");
}
Hello ();
Hello ();
</script>
We can see clearly from the above code that the function is also a data and a variable, and we can assign a value to the function (re-assign). Of course, in order to prevent such a situation, we can also do this:
Copy Code code 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 paragraphs, the JS engine will not put them together.