Home > Web Front-end > JS Tutorial > JavaScript function scope_basic knowledge

JavaScript function scope_basic knowledge

WBOY
Release: 2016-05-16 16:31:36
Original
1159 people have browsed it

In some programming languages ​​​​like C, each piece of code within curly braces has its own scope, and variables are not visible outside the code segment where they are declared. We call this block-level scope ( block scope), and there is no block-level scope in JavaScript. Instead, JavaScript uses function scope: a variable is defined within the body of the function in which it is declared, as well as within the body of any functions within which it is nested. In the following code, i, j and k defined in different positions are all defined in the same scope

Copy code The code is as follows:

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);//Output 0-9 
                                                                            alert(k);//output 10
}  
alert(j);//output 0
}



The function scope of JavaScript means that all variables declared inside the function are always visible within the function body. Interestingly, this means that the variable is already available before it is even declared. This feature of JavaScript is informally called hoisting, that is, all variables declared in the JavaScript function body (not involving assignment) are "advanced" to the top of the function body. Look at the following code

Copy code The code is as follows: var global="globas";
function globals()
{
alert(global);//undefined
var global="hello QDao";
alert(global);//hello QDao
}



Due to the characteristics of function scope, local variables are always defined in the entire function body, which means that variables within the function body cover global variables with the same name. However, local variables are not actually assigned until the program executes the var statement. Therefore, the above process is equivalent to: "advancing" the variable declaration within the function to the top of the function body, while leaving the variable initialization at the original position. :

Copy code The code is as follows: var global="globas";
function globals()
{

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



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template