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

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

    examples without brackets:

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

    (this is the only real use of void, afaik)

    or

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

    or

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

    work as well. the void is causing the expression to evaluate, as well as the assignment and the bang. the last one works with ~, +, -, delete, typeof, some of the unary operators (void is one as well). not working are of couse ++, -- because of the requirement of a variable.

    the line break is not necessary.

提交回复
热议问题