Variable scope
The position of a variable or the scope of its effect, which is also called the scope.
If a variable is declared within a function, the scope is only within the function and cannot be called outside the function. When the function call finishes executing, the variables within the function are immediately destroyed .
function
getArea(length,width){
// 局部变量area,在函数调用后立马销毁
var
area= length*width;
return
area;
}If a variable is declared outside of a function, its scope is global, also called a
global variable . After the page is loaded by the browser, the global variable is stored in memory until the page is closed for destruction.
<!DOCTYPE html>
<
html
lang
=
"zh"
>
<
head
>
<
meta
charset
=
"UTF-8"
>
<
title
>计算桌子面积的函数</
title
>
</
head
>
<
body
>
<
script
>
window.onload=function (ev) {
// 声明一个变量,用于临时存储桌子的长度
var length=80;
// 声明一个变量,用于临时存储桌子的宽度
var width = 60;
// area 是全局变量,它在函数外
var area=getArea(length,width);
document.write(" 桌子的面积是"+area+"<
br
>");
}
function getArea(length,width){
// 局部变量area,在函数调用后立马销毁
var area= length*width;
return area;
}
</
script
>
</
body
>
</
html
>two variable name area, because the declared position is different, within the function is called a local variable, and the outside of the function is called the global variable.
Javascript&jquery. Variable Scope