The unique var pattern in the body of the JavaScript base function (002)

Source: Internet
Author: User

Global variables are not good. So when it comes to the fame variable, you should use the unique var pattern in the function body (single Var). This model has a number of benefits:

    • Provides a unique place to see the variables in the body of the function
    • Always fame before using a variable, so uninitialized variables are assigned a value of undefine.
    • Make you remember to have a reputation variable. :-)
    • The code is more concise (because it turns multiple var into one)

It is easy to say that this pattern is the first in the function body, with a var reputation all local variables (variable).

function func () {var a = 1,b = 2,sum = A + B,myobject = {},i,j;//Functions body ...}

Here is a common problem with the local variables in a JavaScript function: hoisting. Hoisting can be understood as the "lifting" of a variable's reputation within a function. To explain this phenomenon, take a look at the following code:

Antipatternmyname = "global"; Global variablefunction func () {    alert (myname);//"undefined"    var myname = "local";    alert (myname); "Local"}func ();

The first use of myname in a function would have been to call a global variable, but the result would have been undefined, because JavaScript allowed the Var reputation to be reused anywhere, and the effect was the same as in the function body when using the var reputation variable in the middle of the function body. , but the fame is the fame, but has not yet initialized, this has appeared the undefined situation. So the above code is equivalent to the following:

myname = "global"; Global variablefunction func () {    var myname;//Same as-var myname = undefined;    alert (myname); "Undefined"    myname = "local";    alert (myname); "Local"}func ();

The unique var pattern in the body of the JavaScript base function (002)

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.