Role
Declare a function, such as declaring a variable.
Grammar
?
Omit Var
In JavaScript, if you omit the var keyword and assign it directly, the variable is a global variable, even if it is defined in a function.
?
12345678 |
<script type= "text/javascript" > function Define() { a = 2; } function Hello() { alert(a); } </script> |
As the code shows, after running the function define (), the variable A is declared as a global variable. You can refer to variable A in the Hello () function.
More specific examples
We all know that the Var keyword in JavaScript is used to declare a variable, but if you write the variable name directly without the keyword, and then assign it to it, JavaScript does not give an error, and it automatically declares the variable. Does it mean that the Var in JavaScript is an extra thing? Obviously not!
Take a look at the following code:
?
12345678 |
str1 = ‘Hello JavaScript!‘ ; function fun1() { str1 = ‘Hello Java!‘ ; } fun1(); alert(str1); // 弹出 Hello Java! |
As you can see, after the function fun1 is called, the value of str1 is changed within the function.
Then make a slight change to the above code:
?
12345678 |
str1 = ‘Hello JavaScript!‘ ; function fun1() { var str1 = ‘Hello Java!‘ ; } fun1(); alert(str1); // 弹出 Hello JavaScript! |
See no, the value of str1 is not changed by the function fun1.
Obviously, the VAR keyword affects the scope of the variable.
Outside the function: variables are global variables, whether or not they are declared with Var.
Inside the function: If the variable does not use the var keyword declaration, then it is a global variable, only with the Var keyword declared, is the local variable.
Conclusion
To avoid potential risks, be sure to use the VAR keyword to declare variables.
How to use the var keyword in javascript