1 // 反模式,仅用于演示 2 3 // 全局函数 4 function foo() { 5 alert('global foo'); 6 } 7 function bar() { 8 alert('global bar'); 9 } 10 11 function hoistMe() { 12 13 console.log(typeof foo); // "function" 14 console.log(typeof bar); // "undefined" 15 16 foo(); // "local foo" 17 bar(); // TypeError: bar is not a function 18 19 // 函数声明: 20 // 变量foo和它的定义实现都被提前了 21 22 function foo() { 23 alert('local foo'); 24 } 25 26 // 函数表达式: 27 // 只有变量bar被提前,它的定义实现没有被提前 28 var bar = function () { 29 alert('local bar'); 30 }; 31 } 32 hoistMe();
函数声明可以提前,但是匿名函数表达式却不行。