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

前端 未结 19 1531
走了就别回头了
走了就别回头了 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:16

    My understanding of the asker's question is such that:

    How does this magic work:

    (function(){}) ('input')   // Used in his example
    

    I may be wrong. However, the usual practice that people are familiar with is:

    (function(){}('input') )
    

    The reason is such that JavaScript parentheses AKA (), can't contain statements and when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.

    Source: blog post Immediately-Invoked Function Expression (IIFE)

提交回复
热议问题