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)