预解析(变量提升)
全局下的预解析
js代码运行到浏览器,浏览器提供了一个供js代码执行的环境,在代码执行之前先进行了预解析;会把全局作用域下所有带有var 和 function关键字的进行预解析 (全局作用域下预解析)(预解析完成代码从上到下执行)
预解析分为以下两部分
-
声明:var a; 只是声明了没有赋值
-
定义 a = 100; 赋值的操作
预解析的时候,带有var关键字的是只声明不定义,而带有function关键字是声明+定义
console.log(a,b);//undefined undefined var a = 10; var b = 10; console.log(a,b);//10 10 fn(); function fn(){ console.log("哈哈"); } fn(); fn();
预解析流程图: