预解析
-
解析器运行 JS 分为哪两步:预解析+执行代码
预解析: js 引擎会把 js里面所有 var 还有 function 提前到当前作用域的最前面
执行代码:从上到下执行
预解析分为:变量预解析(变量提升) 和函数预解析(函数提升)
-
变量提升的步骤和运行过程:
就是把所有的变量声明提升到当前作用域的最前面,不提升赋值操作
这里先定义了函数,但是没有赋值就调用
-
函数提升的步骤和运行过程
就是把所有函数声明提升到当前作用域的最前面,不调用函数
例子
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 = b = c = 9;
//相当于 var a = 9;b = 9;c = 9; b 和 a 没有var声明,当全局变量看
//集体声明的写法: var a = 9, b = 9 ,c = 9;
console.log(a); //9
console.log(b); //9
console.log(c); //9
}
f1();
console.log(c); //9
console.log(b); //9
console.log(a); // 报错