JavaScript Learning Notes 2 Function _ Basics

Source: Internet
Author: User
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.

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.