【问题标题】:Why is this grouping operator + function immediately invoked为什么这个分组运算符 + 函数立即被调用
【发布时间】:2013-01-26 11:37:38
【问题描述】:

我正在研究立即调用函数表达式 (IIFE) 的行为,在此过程中我遇到了以下情况。

(function () {
    document.write("bar");
})

(function () {
    document.write("foo");
}());

我以为第一个只是一个分组运算符,里面有一个函数表达式,没有调用它。第二个是分组运算符以及函数表达式,但现在调用该函数。

我觉得奇怪的是两者都被调用了,这是为什么呢?

(function () {
    document.write("bar");
})

var x = 1;

(function () {
    document.write("foo");
}());

当我通过在两者之间插入一个变量声明来打破这两者时,它只是写了 foo.这正是我所期望的。

【问题讨论】:

标签: javascript iife


【解决方案1】:

因为你忘记了第一个函数表达式后面的分号:

(function () {
    document.write("bar");
});

否则第二个“分组运算符”被解释为函数调用。所以这个:

(function a() {
    ...
})

(function b() {
    ...
}());

基本相同:

function b() {
    ...
}

(function a() {
    ...
})(b());

重新排序使其更易于查看。请记住,空白字符在 JavaScript 中没有意义,会被忽​​略。

【讨论】:

    【解决方案2】:

    正如 Felix Kling 正确指出的:缺少的分号导致第二个 IIFE 周围的括号被解释为 函数调用,而不仅仅是对函数表达式进行分组。没有换行符会变得更加清晰:

    (function () {
        document.write("bar");
    })(function () {
        document.write("foo");
    }());
    

    或者进行一些重新调整:

    (function () {
        document.write("bar");
    })(
        function () {
            document.write("foo");
        }()
    );
    

    第一个函数表达式被调用,第二个函数表达式的结果作为它的第一个也是唯一的参数。您还应该注意,foobar 是写而不是 barfoo,因为首先调用第二个函数,并将其结果作为参数传递给第一个函数。

    【讨论】:

      【解决方案3】:

      你也可以这样写一个 IIFE:(function () {})()

      通过省略分号,您的第一个代码 n-p 实际上调用了第一个函数,第二个 IIFE 作为第一个的参数传递。

                          executing as parameter for the first IIFE
                                                     \/ 
      (function () {document.write("bar");})( (function () {document.write("foo");}());)
      

      首先打印foo 然后bar 不像:

      (function () {
          document.write("bar");
      })();
      
      (function () {
          document.write("foo");
      }());
      

      打印barfoo

      (function () {
          document.write("bar");
      });
      
      (function () {
          document.write("foo");
      }());
      

      其中第一个现在仅被视为分组运算符。

      【讨论】:

        猜你喜欢
        • 2023-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多