Explain the encapsulated anonymous function syntax

后端 未结 10 1666
时光说笑
时光说笑 2020-11-21 07:02

Summary

Can you explain the reasoning behind the syntax for encapsulated anonymous functions in JavaScript? Why does this work: (function(){})(); but

10条回答
  •  生来不讨喜
    2020-11-21 07:11

    Perhaps the shorter answer would be that

    function() { alert( 2 + 2 ); }
    

    is a function literal that defines an (anonymous) function. An additional ()-pair, which is interpreted as an expression, is not expected at toplevel, only literals.

    (function() { alert( 2 + 2 ); })();
    

    is in an expression statement that invokes an anonymous function.

提交回复
热议问题