In the outermost definition is the global variable
If you do not use VAR to declare directly assigned variables inside a function, then this variable is also a global variable
Variables declared with Var inside a function are called local variables
Defined at the beginning of the global variable in the entire JS range can be accessed, can be used, defined in the indefinite position of the global variable, only after the definition of variables to use the variable, if a variable is defined in a function, and declared with Var, it is a local variable, only valid in the method body, parameters are local variables , in the method body, can not be accessed, if the variable is assigned directly in the body of the method, without Var declaration, it is a global variable, but only after the function is executed to be externally accessible, if not executed, this variable can still access the
The return value of a function can be used as a parameter to another function, so that the callback function
123456789101112131415161718 |
<
script
>
window.onload=function(){
var y=1;//属于全局变量
function show(x){
var num=2;
sum=3;
return num*x;
}
//show();
//alert(num);出现错误,num的作用域仅限于方法体内
//alert(x);出现错误,参数a的作用与仅限于方法体内
alert(sum);//弹出sum的值,方法体内不用var声明的变量,不仅仅作用于方法体内,相当于全局变量(注意,只有在方法运行后才能访问到,否则会提示sum is not defined)
function fun(){
return 5;
}
alert(show(fun()));//这属于回调函数,回调函数是将一个函数的返回值直接作为另一个函数的参数进行计算的方式
}
</
script
>
|
JS local variables and global variables