The code copy is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
/*
* 1. All variables in js are common.
2.js does not have static variables
3. Closure: variables outside the function can be called inside the function; otherwise, it cannot
*/
var r=10;
function test1(){
var r2="abc";
//alert(r)
}
//alert(r2);//r2 inside the function that cannot be accessed
test1();
//Nested functions are OK
function test2(num1){
function test3(num2,num3){
return num2+num3+num1;
}
return test3(10,20)
}
//alert(test2(30));
//-----------------------------------------------------------------------------------------------------------------------------
function testfun(){
var r=1;
var arr=[];
for(var x=0;x<3;x++){
r++;
arr[x]=function(){
return r;
}
}
return arr;
}
alert("testfun:"+testfun());
var arr2=testfun();
alert("arr:"+arr2[0]);
alert("arr:"+arr2[1]());
alert("arr:"+arr2[2]());
//=========== The above three pop-up boxes are all 4===============================
/*Analyze the reasons:
Understand what functions are in JavaScript?
A function is an executable block of code, and a function can also be represented by a variable, such as the second way of defining a function.
var add=new Function("a","return a+10"); The underlying essence is the function name pointer
This executable code created for variables.
* First, after the testfun function is executed, the same is stored in arr[0], arr[1], and arr[]
Executable code block function(){
Return r
} In other words, the above three are just function variables. To execute them, you only need to add () after the variable name and it will be OK.
And at this time the value of r is 4
When executing arr[0]() is equivalent to executing the code in this code block.
So the final result returns r, of course, returns 4.
*/
</script>
</head>
<body>
</body>
</html>