js中创建函数的两种方法:
1 //一、函数声明 2 function foo(){ 3 4 }
//二、函数表达式 var foo=function(){ }
虽然这两种方法都创建了一个foo的函数,但他们之间还是有区别的,因为在JavaScript中,有一种函数(变量)声明提升(hoisting)机制,即函数或者变量无论在哪里声明,总是被提升到作用域的最前面
1 alert(hello); 2 function hello(){ 3 return "hello!"; 4 }//函数声明被提升到最上面,所以弹出"hello!"
5 alert(hello); 6 var hello=function(){ 7 return "hello!"; 8 }//使用var声明的变量hello也被提升到上面,只是被赋值undefined,所以弹出undefined