Javascript function scope learn the example of of js scope

  • 2020-03-30 01:19:17
  • OfStack

In some programming languages like c, each piece of code in curly braces has its own scope, and variables are not visible outside the code segment where they are declared. This is called block scope, and javascript has no block-level scope. Instead, javascript USES a function scope: a variable is defined in the body of the function in which it is declared and in any function in which that body is nested. In the following code, I,j, and k are defined in different locations within the same scope


function text(o)   
{   
    var i=0;   
    alert(typeof o);   
    if(typeof o == "string")   
    {   
        var j=0;   
        for(var k=0;k<10;k++)   
        {   
            alert(k);//0-9    
        }   
        alert(k);//Output 10    
    }   
    alert(j);//0    
}

Javascript's function scope means that all variables declared inside a function are always visible inside the function. Interestingly, this means that variables are even available before they are declared. This feature is informally called javascript statement (hoisting) ahead of time, namely the javascript function declaration of all of the variables (not involving the assignment) are "early" to the top of the function body. Look at the following code


var global="globas";   
function globals()   
{   
    alert(global);//undefined   
    var global="hello QDao";   
    alert(global);//hello QDao   
}

Due to the characteristic of function scope, local variables are always defined in the whole function body, that is, the global variables with the same name are hidden in the internal variables of the function body. However, local variables are not actually assigned until the var statement is executed. Therefore, the above procedure is equivalent to declaring variables in a function "ahead" to the top of the function body, and initializing variables in the same place:


var global="globas";   
function globals()   
{   

       var global;   
    alert(global);//undefined   
    global="hello QDao";   
    alert(global);//hello QDao   
}


Related articles: