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

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

    Another point of view

    First, you can declare an anonymous function:

    var foo = function(msg){
     alert(msg);
    }
    

    Then you call it:

    foo ('Few');
    

    Because foo = function(msg){alert(msg);} so you can replace foo as:

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

    But you should wrap your entire anonymous function inside pair of braces to avoid syntax error of declaring function when parsing. Then we have,

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

    By this way, It's easy understand for me.

提交回复
热议问题