It is perfectly legal for JavaScript to ignore the VAR keyword when declaring a variable. JavaScript, as a weakly typed (loosely-typed) language, does not declare the variable type to be understandable, but the fact is not so straightforward, because the properties of a variable are scoped beyond the type. The following examples illustrate:
the
<script language= "JavaScript" >var a = 0;document.write (A + ' <br> '); var b = 1;function foo () {document.write (b + ' <br> ');d ocument.write (window.b); var b = 1;} Foo ();</script>
Results show:
0
Undefined
1
Note: variable elevation hoisting: Before execution, the code is loaded into memory, and the declaration of a variable in function is "lifted" to the front of the function, with the other order unchanged. However, in the actual development is not advocated written in the back, the above funtion equivalent to:
<script language= "JavaScript" >var a = 0;document.write (A + ' <br> '); var b = 1;function foo () {var bdocument.wri Te (b + ' <br> ');d ocument.write (window.b); = 1;} Foo ();</script>
No.2
<script language= "JavaScript" > A = 0;document.write (A + ' <br> '); b = 1;function foo () {document.write (b + ' <br> ');d ocument.write (window.b+ ' <br> '); b = 2;document.write (+ + ' & Lt;br> ');d ocument.write (window.b);} Foo ();</script>
Results show:
0
1
1
2
2
Summary: Var declares a local variable (extension: scope), and without Var, the variable defaults to global.
Articles in the Var keyword in javascript