The difference between var and no var when javascript defines variables
- 2020-03-30 03:33:07
- OfStack
Let's start with a piece of code
function show(){
alert(abc);
}
var abc="defg";
show();
Someone with programming experience in C++ or Java might say, "this program is dead, a variable is defined after a function that references it, and the bug will kill you." Run it in a browser, and what happens? Perfect run! So let's talk about what's going on here -- the difference between a variable that has var and one that doesn't have var defined.
1. No var
Simply put, it is not safe to omit var when defining variables, but it is legal. The interpreter gives the variable global scope regardless of where it is defined.
2, a var
Safe, legal. The scope of a defined variable depends on the location of the definition. For details on what scope is, see "javascript scope" in this blog.
In this way, the initial problem can be solved. In the function is the definition of ABC, but the value is undefined, so ABC has global scope, and out of the function is just an update to the value of ABC.