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

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

    The code you show,

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

    consist of two statements. The first is an expression which yields a function object (which will then be garbage collected because it is not saved). The second is an expression which yields a string. To apply the function to the string, you either need to pass the string as an argument to the function when it is created (which you also show above), or you will need to actually store the function in a variable, so that you can apply it at a later time, at your leisure. Like so:

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

    Note that by storing an anonymous function (a lambda function) in a variable, your are effectively giving it a name. Hence you may just as well define a regular function:

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

提交回复
热议问题