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

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

    (function (msg){alert(msg)})
    ('SO');
    

    This is a common method of using an anonymous function as a closure which many JavaScript frameworks use.

    This function called is automatically when the code is compiled.

    If placing ; at the first line, the compiler treated it as two different lines. So you can't get the same results as above.

    This can also be written as:

    (function (msg){alert(msg)}('SO'));
    

    For more details, look into JavaScript/Anonymous Functions.

提交回复
热议问题