上面这段代码中,函数声明在函数调用下,为何会调用成功呢?函数
hello(); function hello(){alert("hello");}
由于js在编译阶段预解析,将上面这段代码转换成:spa
var hello = function(){alert('hello');}; hello();
只有函数声明才会被提高,函数表达式在预解析阶段不会被提高。code
再看一个案例:blog
var a=1; function hello(){ console.info(a); var a=2; }
执行结果为何是undefined呢?io
由于在预解析阶段,代码被转换成下面:console
var a=1; function hello(){ var a; console.info(a); a=2; }
因此执行结果是undefined编译
这就是为何js函数中变量声明建议写在最前面:function
function hello(){ var a=1,b=2; console.info(a); }