Domain parsing: var Distribution

Source: Internet
Author: User

In JavaScript, you can declare multiple var statements at any position of the function, and they serve as if they were declared at the top of the function, this behavior is called hoisting (mounting/top resolution/pre-resolution ). When you use a variable and then re-declare it in the function, logical errors may occur. For JavaScript, you only need that your variables are in the same scope (the same function) and they are declared, even when they are used before the VaR declaration. Let's look at the example below:

// Counterexample myname = "Global"; // global variable function func () {alert (myname); // "undefined" Var myname = "local"; alert (myname ); // "local"} func ();

In this example, you may think that the first alert is "Global" and the second alert is "loacl ". This expectation is understandable, because at the first alert, myname was not declared. At this time, the function will naturally look at the global variable myname. However, this is not actually the case. The first alert will pop up "undefined" because myname is treated as a local variable of the function (although declared later), and all the variable declarations will be mounted to the top of the function. Therefore, to avoid such confusion, it is best to declare all the variables you want to use in advance.

The execution of the above code snippet may be like the following:

Myname = "Global"; // global variablefunction func () {var myname; // equivalent to-> var myname = undefined; alert (myname ); // "undefined" myname = "local"; alert (myname); // "local"} func ();


Domain parsing: var Distribution

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.