The difference between adding var and not adding var when javascript defines a variable
- 2020-05-09 18:06:23
- OfStack
1. The external is the global, and the internal is the local variable.
2. Add var as a local variable (within the method), and leave var as a global variable (after the method has been used once)
<script type="text/javascript">
var golbe="global";
test();
function test(){
var local="local";
document.write(golbe);
document.write(local);
}
document.write(golbe);
document.write(local);
</script>
In the test method above, when var of local is removed, local becomes a global variable, but if local is not used locally, local is not valid as a global variable.
To verify this, I comment out the code inside the test method where only 1 USES the local variable.
Conclusion: global variables can not declare var function variables must declare var, the definition of global variables without or without the var keyword does not matter; But if you define a local variable without the var keyword, the javascript interpreter will interpret it as a global variable.