1. Variables
ECMAscript variables are loose variables. The so-called loose variables means that the variable name can hold any type of data. Each variable is just a placeholder for saving the value.
Definition: var firstDemo;
2. The scope of variables
2.1 Basic Concept
Use var to define variables: define local variables that define the scope of the variable. This method of defining variables is also an explicit declaration.
If you don't understand this, you can take a look at the following simple and crude example:
The code copy is as follows:
test();
function test(){
var firstDemo="hello";//Define local variables
alert(firstDemo);//hello
}
test();
function test(){
var firstDemo="hello";//Define local variable firstDemo
}
alert(firstDemo);//Report an error, firstDemo is not defined
From the above two examples, if a variable is defined using var in a function, the variable will be destroyed after the function exits.
Omit var to define variables: As long as the function that defines the variable is called once, the variable can be accessed globally. This method of defining variables is also an implicit declaration
The code copy is as follows:
<script type="text/javascript">
test();
alert(firstDemo); //hello
function test(){
firstDemo="hello";
}
</script>
tips: The explicitly declared variable is already compiled into the calling object at precompilation (for example, var t=1; var t=1 when precompiled; t=1 when interpreted;) Unlike the implicitly declared variables that are defined as global variables only when interpreted.
Figuring out the scope of variables can help us think about how to declare variables reasonably, which not only reduces unnecessary memory overhead, but also greatly avoids the trouble caused by repeated definitions of variables and overwriting previously defined variables.
2.2 Scope Analysis
The code copy is as follows:
<script type="text/javascript">
function demoFunction(s){
document.writeln(s)
}
var i=0; //Define global variable
function test(){
demoFunction(i);
function innerFunction(){
var i = 1; //Define local variables
demoFunction(i);
}
innerFunction();
demoFunction(i);
}
test();
</script>
Output result: 0 1 0
The code copy is as follows:
<script type="text/javascript">
function demoFunction(s){
document.writeln(s)
}
var i=0;
function test(){
demoFunction(i);
function innerFunction(){
demoFunction(i);
var i=1;
demoFunction(i);
}
innerFunction();
demoFunction(i);
}
test();
</script>
Output result:
A, 0 0 1 0
B, 0 undefined 1 0
C, 0 error i is not defined
You can guess which one is the result, and the reason will be explained in detail in the message.
The above is all about this article. Simply put, the scope of variables in any programming language is a very critical detail. The scope of variables in JS is relatively freer than that of languages such as JAVA and C. A big feature is that JS variables have no block-level scope, and variables in functions are valid in the entire function.