JavaScript variable Scope detailed

Source: Internet
Author: User
Tags define local variable scope

JavaScript variable Scope detailed

The scope of a variable is the region in the program that defines the variable. The scope of a variable is also called a scope, which refers to the valid range of a variable in the program. Depending on the scope, variables can be divided into global variables and local variables.


Put a piece of code first, and if the reader is not confused about the output of the code, don't read it down.


The variable scope of JavaScript is based on its unique scope chain.
JavaScript does not have block-level scopes.
Variables declared in a function are defined throughout the function.


/* Code 1 * *
var scope = "global";
function Checkscope () {
var scope = "local";
function Childcheck () {
var scope = "Childlocal";
document.write (scope);
}
function childundefined () {
document.write (scope);
var scope;
}
function Childoverride () {
Scope = "Childoverride";
document.write (scope);
}
document.write (scope); Output "local"
Childcheck (); Output "Childlocal"
Childundefined (); Output "undefined"
Childoverride (); Output "Childoverride"
document.write (scope); Output "Childoverride"
}
Checkscope (); Output "Local childlocal undefinedchildoverride childoverride"
document.write (scope); Output "global"

Global scope and local scope
Global variables are global in scope and are defined everywhere in JavaScript, and variables declared within functions are local variables that are local in scope and are defined only within the body of the function. For the following output readers should not be surprised.
/* Code 2 * *
var scope = "global";
function Checkscope () {
var scope = "local";
document.write (scope);
}
Checkscope (); Output "local"
document.write (scope); Output "global"

Variables can be used in global variable scopes without the Var statement, but if the local variable is declared to be certain to use the Var statement, it is considered a reference to the global variable. Look at the following code:

/* Code 3 * *
var scope = "global";
function Checkscope () {
Scope = "local";
document.write (scope);
}
Checkscope (); Output "local"
document.write (scope); Output "local"

No block scope
JavaScript does not have a block-level scope, and the variables declared in the function are defined throughout the function. The following code may be quite unexpected to unfamiliar readers:

/* Code 4 * *
var scope = "global";
function Checkscope () {
document.write (scope); Statement 4.1
var scope = "local"; Statement 4.2
document.write (scope);
}
Checkscope (); Output "Undefinedlocal"

Because the statement 4.1 (var scope = "local";) the variable declared is valid throughout the Checkscope function scope, the statement 4.2 (document.write (scope); A local variable is referenced at the time of execution, and the local variable scope is not defined, so output "undefined". So a good programming habit is to put all the variable declarations together and place them at the beginning of the function.

Once you know the above, it's not confusing for the reader to look at code 1 again.

object's Property variable
The object's property variable is easier to understand, so look at the code below and the reader should not be confused.
/* Code 5 * *
var scope = "global";
var obj = new Object ();
Obj.scope = "Object";
Obj.checkscope = function () {
var scope = "Loacl";
document.write (scope); Output "Loacl"
document.write (This.scope); Output "Object"
document.write (Window.scope); Output "global"
}
Obj.checkscope (); Output "Loacl object Global"


Look at the following code:

<script type= "text/web Effects"
    var rain = 1;
    function Rainman () {
& nbsp;       var mans = 2;
        function inner () {
             var innervar = 4;
            alert (rain);
       }
        Inner ();   //Call inner function
   }
    Rainman ();   //Call the Rainman function
</script>
Observe alert (rain), the code. JavaScript first looks in the inner function to see if the variable is defined rain, if it is defined, use the rain variable in the inner function, or if the rain variable is not defined in the inner function, JavaScript continues to look in the Rainman function to see if the rain variable is defined, in which the rain variable is not defined in the Rainman function body, and the JavaScript engine continues to look up (the global object) to see if it defines rain In the global object we defined rain = 1, so the end result would pop ' 1 '.

Scope chain: When JavaScript needs to query for a variable x, it first looks for the first object in the scope chain, and if the first object does not define an X variable, JavaScript continues to find that there are no X variables defined, and if the second object is undefined, it continues to find, and so on.

The above code involves three scope chain objects, followed by: Inner, Rainman, window.

2. Within the function body, local variables have higher precedence than global variables of the same name.
<script type= "Text/javascript" >
var rain = 1; Define Global Variables Rain
function Check () {
var rain = 100; Define local variables Rain
alert (rain); 100 will pop up here.
}
Check ();
alert (rain); 1 will pop up here.
</script>3 and JavaScript do not have block-level scopes.
This is also a more flexible part of JavaScript than other languages.

With a careful look at the following code, you will find that the variables I, j, K scopes are the same, and they are global throughout the rain function.

<script type= "Text/javascript" >
function Rainman () {
There are three local variables I J k in the Rainman function body
var i = 0;
if (1) {
var j = 0;
for (var k = 0; k < 3; k++) {
Alert (k); Eject 0 1 2 respectively
}
Alert (k); Pop up 3
}
Alert (j); Pop up 0
}
</script>
4, the variables declared in the function are defined throughout the function.
First, look at this piece of code:

<script type= "text/javascript"
    function Rain () {
         var x = 1;
        function Man () {
             x = 100;
       }
        Man ();       //Call man
        alert (x);   ///This will pop up
   }
    Rain ();   //Call rain
</script>
The code illustrates that variable x can be used throughout the rain function and can be assigned a new value. Because of this rule, there will be "unthinkable" results, observe the following code.

<script type= "Text/javascript" >
var x = 1;
function Rain () {
alert (x); Pop ' undefined ' instead of 1
var x = ' Rain-man ';
alert (x); Pop ' Rain-man '
}
Rain ();
</script>
is because the local variable x in the function rain is defined throughout the function (Var x= ' Rain-man ', declared), so a global variable x with the same name is hidden throughout the rain function body. The reason for this is that the ' undefined ' is ejected because the local variable x is still not initialized when the first execution of alert (x) is performed.

So the rain function above is equivalent to the following function:

function Rain () {
var x;
alert (x);
x = ' Rain-man ';
alert (x);
}
5. Variables not defined using the VAR keyword are global variables.
<script type= "Text/javascript" >
function Rain () {
x = 100; The global variable x is declared and assigned
}
Rain ();
alert (x); Will pop up 100
</script>
This is also the common error of JavaScript novice, inadvertently left many global variables.

6, global variables are the properties of the Window object
<script type= "Text/javascript" >
var x = 100;
alert (window.x);//Eject 100
alert (x);
</script>
Equivalent to the following code

<script type= "Text/javascript" >
window.x = 100;
alert (window.x);
Alert (x)
</script>

Within a function, a local variable has a higher precedence than a global variable of the same name, and if there are local variables with the same names as global variables, or if a parameter with the same name as a global variable is declared inside the function, then the global variable will no longer work. The following example:

<script language= "javascript" type= "Text/javascript" >
<!--
var a = "I am a global variable";
function Check ()
{
var a = "I am a local variable";
document.write (a);
}
Check ();
-->
</script>
Output:

I am a local variable
Although you can declare a variable in a global scope without using VAR, you must use the VAR statement when declaring a local variable. In general, a function does not know what variables are defined in the global scope, nor does it know the role of these variables. If a function uses a global variable instead of a local variable, it can change the value of a global variable that is dependent on other parts of the program. Therefore, it is a good idea to use the VAR statement when declaring all the variables.

JavaScript does not have a block-level scope, and all variables declared in a function, wherever declared, are meaningful throughout the function. In the following code, the variable i,j,k scope is the same, and is meaningful throughout the function body. Look at the following example:

<script language= "javascript" type= "Text/javascript" >
<!--
function Check ()
{
var i = 0;
if (i = = 0)
{
var j = 1;
for (var k = 0;k < 1;k + +)
{
document.write ("K in the circulation body value is:" + k + "<br/>");
}
document.write ("K in the circulation body value is:" + k + "<br/>");
}
document.write ("J is the value outside of the IF statement:" + j);
}
Check ();
-->
</script>
Output:

K in the circulation body values are: 0
K in the circulation body values are: 1
J The value outside of the IF statement is: 1

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.