Original: Learn JavaScript from the beginning (ii)--variables and their scopes
One, variable
ECMAScript variables are loose variables, so-called loose variables, that is, variable names can hold any type of data, each variable is just a placeholder for holding the value.
Definition: var Firstdemo;
Ii. Scope of variables
2.1 Basic Concepts
Use Var to define a variable: A local variable that defines the scope of the variable, and the method that defines the variable is also declared explicitly.
If you don't understand that, you can take a look at this simple, rough example:
Test ();
function Test () {
var firstdemo= "Hello"; // Defining Local Variables
alert (Firstdemo); // Hello
}
function Test () { var firstdemo= "Hello"; define local variable Firstdemo } alert (Firstdemo); // error, Firstdemo is not define
As can be seen from the above two examples, if you use var to define a variable in a function, the variable will be destroyed after the function exits.
Omit var to define a variable: The variable can be accessed globally whenever a function that defines the variable is called once. This method of defining variables is also an implicit declaration
<script type= "Text/javascript" > Test (); alert (Firstdemo); Hello function Test () { Firstdemo= "Hello"; } </script>
tips: explicitly declared variables are compiled into the calling object at precompilation, such as Var t=1, var t on precompilation, execution of t=1 on interpretation, or a global variable when an implicit declaration variable is interpreted.
Figuring out the scope of a variable can help us think about how to reasonably declare a variable, which reduces unnecessary memory overhead while greatly avoiding the hassle of overwriting a previously defined variable with a duplicate definition of a variable.
2.2 Scope Analysis
<script type= "Text/javascript" > function demofunction (s) { Document.writeln (s) } var //Definition function Test () { demofunction (i); function innerfunction () { var// } Innerfunction (); } Test (); </script>
Output results: 0 1 0
<script type= "Text/javascript" >
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 am not defined
You can guess what the result is, the reason will be in the message to explain.
Learn JavaScript from the beginning (ii)--variables and their scopes