Home > Web Front-end > JS Tutorial > Detailed explanation of the use of var keyword in JavaScript_Basic knowledge

Detailed explanation of the use of var keyword in JavaScript_Basic knowledge

WBOY
Release: 2016-05-16 15:45:11
Original
1108 people have browsed it

Function
Declaration function; such as declaring a variable.
Grammar

var c = 1; 
Copy after login

Omit var
In JavaScript, if you omit the var keyword and assign a value directly, then this variable is a global variable, even if it is defined in a function.

<script type="text/javascript"> 
  function Define() { 
    a = 2; 
  } 
  function Hello() { 
    alert(a); 
  } 
</script> 
Copy after login


As shown in the code, after running the function Define(), the variable a is declared as a global variable. Variable a can be referenced in the Hello() function.

More specific examples
We all know that the var keyword in JavaScript is used to declare variables, but if you do not use this keyword and directly write the variable name, and then assign it to it, JavaScript will not report an error, it will automatically declare the variable . Could it be that var in JavaScript is redundant? Obviously not!

Please look at the following code:

str1 = 'Hello JavaScript!';
function fun1() {
 str1 = 'Hello Java!';
}
fun1();
alert(str1);

// 弹出 Hello Java!

Copy after login

As you can see, after the function fun1 is called, the value of str1 is changed within the function.

Modify the above code slightly:

str1 = 'Hello JavaScript!';
function fun1() {
 var str1 = 'Hello Java!';
}
fun1();
alert(str1);

// 弹出 Hello JavaScript!

Copy after login

See, the value of str1 is not changed by function fun1.

Obviously, the var keyword affects the scope of the variable.

External to the function: Variables are global variables regardless of whether they are declared with var or not.

Inside the function: If a variable is not declared with the var keyword, it is a global variable. Only if it is declared with the var keyword, it is a local variable.
Conclusion

To avoid potential risks, be sure to use the var keyword to declare variables.


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template