var scope = "global";
function f() {
alert(scope);//dispaly "undefined" not "global"
var scope = "local";//Vaeiable initized here,but defined everywhere
alert(scope);//display "local"
}
f();
局部变量在整个函数体都是有定义的,这意味着在整个函数体中隐藏了同名的全局变量。虽然局部变量在整个函数体都是定义的,但在执行var语句前,他是不会被初始化的,因此上面的函数f和下面的函数等价
function f() {
var scope;//局部变量在函数头声明
alert(scope); //此处该变量有定义,但值为 "undefined"
scope = "local"; //初始化变量并赋值
alert(scope);//此处该变量具有值
}