Why do you need to invoke an anonymous function on the same line?

前端 未结 19 1494
走了就别回头了
走了就别回头了 2020-11-22 00:17

I was reading some posts about closures and saw this everywhere, but there is no clear explanation how it works - everytime I was just told to use it...:

//          


        
19条回答
  •  盖世英雄少女心
    2020-11-22 01:01

    In summary of the previous comments:

    function() {
      alert("hello");
    }();
    

    when not assigned to a variable, yields a syntax error. The code is parsed as a function statement (or definition), which renders the closing parentheses syntactically incorrect. Adding parentheses around the function portion tells the interpreter (and programmer) that this is a function expression (or invocation), as in

    (function() {
      alert("hello");
    })();
    

    This is a self-invoking function, meaning it is created anonymously and runs immediately because the invocation happens in the same line where it is declared. This self-invoking function is indicated with the familiar syntax to call a no-argument function, plus added parentheses around the name of the function: (myFunction)();.

    There is a good SO discussion JavaScript function syntax.

提交回复
热议问题