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

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

    The IIFE simply compartmentalizes the function and hides the msg variable so as to not "pollute" the global namespace. In reality, just keep it simple and do like below unless you are building a billion dollar website.

    var msg = "later dude";
    window.onunload = function(msg){
      alert( msg );
    };
    

    You could namespace your msg property using a Revealing Module Pattern like:

    var myScript = (function() {
        var pub = {};
        //myscript.msg
        pub.msg = "later dude";
        window.onunload = function(msg) {
            alert(msg);
        };
        //API
        return pub;
    }());
    
    0 讨论(0)
  • 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');
    
    0 讨论(0)
  • 2020-11-22 01:01

    In summary of the previous comments:

    function() {
      alert("hello");
    }();
    

    when not assigned to a variable, yields a syntax error. The code is parsed as a function statement (or definition), which renders the closing parentheses syntactically incorrect. Adding parentheses around the function portion tells the interpreter (and programmer) that this is a function expression (or invocation), as in

    (function() {
      alert("hello");
    })();
    

    This is a self-invoking function, meaning it is created anonymously and runs immediately because the invocation happens in the same line where it is declared. This self-invoking function is indicated with the familiar syntax to call a no-argument function, plus added parentheses around the name of the function: (myFunction)();.

    There is a good SO discussion JavaScript function syntax.

    0 讨论(0)
  • 2020-11-22 01:01

    It is a self-executing anonymous function. The first set of brackets contain the expressions to be executed, and the second set of brackets executes those expressions.

    (function () {
        return ( 10 + 20 );
    })();
    

    Peter Michaux discusses the difference in An Important Pair of Parentheses.

    It is a useful construct when trying to hide variables from the parent namespace. All the code within the function is contained in the private scope of the function, meaning it can't be accessed at all from outside the function, making it truly private.

    See:

    1. Closure (computer science)
    2. JavaScript Namespacing
    3. Important Pair of Javascript Parentheses
    0 讨论(0)
  • 2020-11-22 01:03

    There is one more property JavaScript function has. If you want to call same anonymous function recursively.

    (function forInternalOnly(){
    
      //you can use forInternalOnly to call this anonymous function
      /// forInternalOnly can be used inside function only, like
      var result = forInternalOnly();
    })();
    
    //this will not work
    forInternalOnly();// no such a method exist
    
    0 讨论(0)
  • 2020-11-22 01:07

    This answer is not strictly related to the question, but you might be interested to find out that this kind of syntax feature is not particular to functions. For example, we can always do something like this:

    alert(
        {foo: "I am foo", bar: "I am bar"}.foo
    ); // alerts "I am foo"
    

    Related to functions. As they are objects, which inherit from Function.prototype, we can do things like:

    Function.prototype.foo = function () {
        return function () {
            alert("foo");
        };
    };
    
    var bar = (function () {}).foo();
    
    bar(); // alerts foo
    

    And you know, we don't even have to surround functions with parenthesis in order to execute them. Anyway, as long as we try to assign the result to a variable.

    var x = function () {} (); // this function is executed but does nothing
    
    function () {} (); // syntax error
    

    One other thing you may do with functions, as soon as you declare them, is to invoke the new operator over them and obtain an object. The following are equivalent:

    var obj = new function () {
        this.foo = "bar";
    };
    
    var obj = {
        foo : "bar"
    };
    
    0 讨论(0)
提交回复
热议问题