JavaScript中Function Declaration与Function Expression 或者说 function f(){}和var f=function(){} 的区别
从下面代码感受下
console.log(b); console.log(c); b(); c(); function b () {console.log('b')}; var c = function(){console.log('c')};
可以看出,函数 b 可以正常执行,但函数 c 是 undefined
在JS引擎编译时,Function Declaration 会提升,即无论在哪里声明函数,都会提前到顶部解释
但是Function Expression只有在执行时才会解释,所以 c 当做普通变量一样,只是初始化了,默认是 undefined
Leave a Reply