This article analyzes the difference between var and no var when defining variables in JavaScript. Share it for your reference. The specific analysis is as follows:
Let's take a look at the examples directly:
Copy the code as follows:<script language="javascript" type="text/javascript">
var abc=89;//with var, represent global variable
function test(){
var abc=80;//Inside the function, if you do not have var, it means using a global variable outside the function; with var, it means a new global variable is defined
}
test();
window.alert(abc);
</script>
Strictly speaking: the function does not contain var, which does not mean defining a variable, but rather assigning variables, that is, var abc;abc=8. If the value abc=80 is assigned in the function body (without var), the actual process is like this - this statement first looks for the variable abc in the function body. If it cannot be found, it will continue to look for the variable abc outside the function body. If it still cannot be found, there is no way in the end, and you can only define the variable var abc outside the function body.
So, why
Copy the code as follows: function test(){
abc = 80;
}
This is the reason why the variable abc can be called directly outside the function.
I hope this article will be helpful to everyone's JavaScript programming.