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();

函数声明可以提前,但是匿名函数表达式却不行。

相关文章:

  • 2021-11-08
  • 2021-05-28
  • 2022-12-23
  • 2021-06-08
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-08-09
  • 2022-12-23
  • 2021-11-12
  • 2022-12-23
相关资源
相似解决方案