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

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

    One thing I found confusing is that the "()" are grouping operators.

    Here is your basic declared function.

    Ex. 1:

    var message = 'SO';
    
    function foo(msg) {
        alert(msg);
    }
    
    foo(message);
    

    Functions are objects, and can be grouped. So let's throw parens around the function.

    Ex. 2:

    var message = 'SO';
    
    function foo(msg) {  //declares foo
        alert(msg);
    }
    
    (foo)(message);     // calls foo
    

    Now instead of declaring and right-away calling the same function, we can use basic substitution to declare it as we call it.

    Ex. 3.

    var message = 'SO';
    
    (function foo(msg) {
        alert(msg);
    })(message);          // declares & calls foo
    

    Finally, we don't have a need for that extra foo because we're not using the name to call it! Functions can be anonymous.

    Ex. 4.

    var message = 'SO';
    
    (function (msg) {   // remove unnecessary reference to foo
        alert(msg);
    })(message);
    

    To answer your question, refer back to Example 2. Your first line declares some nameless function and groups it, but does not call it. The second line groups a string. Both do nothing. (Vincent's first example.)

    (function (msg){alert(msg)});  
    ('SO');                       // nothing.
    
    (foo); 
    (msg); //Still nothing.
    

    But

    (foo)
    (msg); //works
    

提交回复
热议问题