javascript function vs. ( function() { … } ());

前端 未结 2 1646
离开以前
离开以前 2020-11-28 11:52

I have often see expressions such as:

(function () {
    var x = 1;
    ...
}());

How do I interpret it? syntactically, this alone is a ano

2条回答
  •  情歌与酒
    2020-11-28 12:35

    Exactly the same, except that it is being invoked immediately after being converted into a function expression.

    // v-----first set of parentheses makes the function an expression
       (function () {
           var x = 1;
           ...
       }());
    //  ^-----this set is used to invoke the function
    

    Same as if you did:

       var myfunc = function () {
           var x = 1;
           ...
       };
       myfunc();
    

    or (similar) this:

       var returnValue = function () {
           var x = 1;
           ...
       }();
    

    Get rid of the names, move the parentheses around, and you can see they're not that different.

提交回复
热议问题