{JS} function statement

Source: Internet
Author: User

The output result of the following statement is as follows:
Alert (f (4 ));
Var f = 0;
Function f (x ){
Return x + 1;
}
Alert (f );

The answer is:
// 5
// 0

Here we need to explain the cause-the reason for this result is that the function definition and variable definition occur at different times.
Function definitions in JS occur during parsing, rather than during runtime. when the JS parser encounters a function definition, it will parse and store (without executing) The statements that constitute the function body, define an attribute with the same name as the function. (If the function definition is nested in other functions, this attribute will be defined in the calling object; otherwise, this attribute will be defined in the Global Object) to save it.

As mentioned above, you can understand why the function definition in JS cannot appear in if/while or other statements, as shown below:
If (a = 1 ){
Function get (param ){
Return param + 1;
}
} Else {
Function get (param ){
Return param + 2; www.2cto.com
}
}

Because the function definition occurs during parsing, The get function is always the second one.


By bill200711022

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.