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

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

    It's just how JavaScript works. You can declare a named function:

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

    And call it:

    foo("Hi!");
    

    Or, you can declare an anonymous function:

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

    And call that:

    foo("Hi!");
    

    Or, you can just never bind the function to a name:

    (function(msg){
       alert(msg);
     })("Hi!");
    

    Functions can also return functions:

    function make_foo() {
        return function(msg){ alert(msg) };
    }
    
    (make_foo())("Hi!");
    

    It's worth nothing that any variables defined with "var" in the body of make_foo will be closed over by each function returned by make_foo. This is a closure, and it means that the any change made to the value by one function will be visible by another.

    This lets you encapsulate information, if you desire:

    function make_greeter(msg){
        return function() { alert(msg) };
    }
    
    var hello = make_greeter("Hello!");
    
    hello();
    

    It's just how nearly every programming language but Java works.

    0 讨论(0)
提交回复
热议问题