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

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

    The simple reason why it doesn't work is not because of the ; indicating the end of the anonymous function. It is because without the () on the end of a function call, it is not a function call. That is,

    function help() {return true;}
    

    If you call result = help(); this is a call to a function and will return true.

    If you call result = help; this is not a call. It is an assignment where help is treated like data to be assigned to result.

    What you did was declaring/instantiating an anonymous function by adding the semicolon,

    (function (msg) { /* Code here */ });
    

    and then tried to call it in another statement by using just parentheses... Obviously because the function has no name, but this will not work:

    ('SO');
    

    The interpreter sees the parentheses on the second line as a new instruction/statement, and thus it does not work, even if you did it like this:

    (function (msg){/*code here*/});('SO');
    

    It still doesn't work, but it works when you remove the semicolon because the interpreter ignores white spaces and carriages and sees the complete code as one statement.

    (function (msg){/*code here*/})        // This space is ignored by the interpreter
    ('SO');
    

    Conclusion: a function call is not a function call without the () on the end unless under specific conditions such as being invoked by another function, that is, onload='help' would execute the help function even though the parentheses were not included. I believe setTimeout and setInterval also allow this type of function call too, and I also believe that the interpreter adds the parentheses behind the scenes anyhow which brings us back to "a function call is not a function call without the parentheses".

提交回复
热议问题