//------原始代码------------
var a = 25;
function abc() {
alert(a);
var a = 10;
}
abc();
//------解析过程------------
var a;
function abc() {
// 局部作用域 预解析
var a;
alert(a);
a = 10;
}
a = 25;
abc();
案例2:
//----------原始代码------------
console.log(a);
function a() {
console.log('aaaaa');
}
var a = 1;
console.log(a);
//------------解析过程-------------
//在预解析的过程中如果函数和变量的名字相同,此时函数优先
var a;
function a() {
console.log('aaaaa');
}
console.log(a);
a = 1;
console.log(a);
案例3
//----------原始代码------------
var a = 18;
f1();
function f1() {
var b = 9;
console.log(a);
console.log(b);
var a = '123';
}
//-----------解析过程------------
var a;
function f1() {
var b;
var a;
b = 9;
console.log(a);
console.log(b);
a = '123';
}
a = 18;
f1();
案例4
//------------原始代码-------
f1();
console.log(c);
console.log(b);
console.log(a);
function f1() {
var a = b = c = 9;
console.log(a);
console.log(b);
console.log(c);
}
//------------解析过程---------------
function f1() {
var a;
a = b = c = 9;
console.log(a);
console.log(b);
console.log(c);
}
f1();
console.log(c); //9
console.log(b); //9
console.log(a); //报错 not defined,因为a是局部变量
-----------------------------------
var a = b = c = 9;这句代码解析为:
var a = 9; //局部变量
//全局变量
b = 9
c = 9;