Javascript learning Note 2 Function

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.