Difference between a named IIFE and calling a name function immediately?

后端 未结 1 614
予麋鹿
予麋鹿 2020-12-04 02:27

Is there any difference between and IIFE

(function foo () {
    var var_of_concern;
}());

and a plain function

function foo         


        
相关标签:
1条回答
  • 2020-12-04 03:19

    The opposite, though it's probably not a serious concern.

    The two are syntactically not the same. The second declares a function and binds it to the local symbol "foo". That function will remain after the function call.

    The IIFE form is syntactically a single expression satement. The second form involves two statements, a function declaration statement and an expression statement (the function call).

    The way that a function call handles local variable declarations has nothing to do with how the function object came into being. If both functions in your example are the same, then there's no difference to how that space is allocated for the local variables in a function call.

    edit — the key syntactic difference is this: the keyword function at the start of a new statement introduces a function declaration statement. That syntactic form does not provide for immediate invocation. That is, this:

    function hello() {
      // some code
    }();  // <---- ERROR
    

    is a syntax error.

    When the function keyword appears in any other context (well, any valid context), then it's not a function declaration — it's a function instantiation (or function definition; I'd have to check the spec) expression. These are all things that can be part of an expression in JavaScript:

     5
     "hello"
     false
     (2 + 5)
     (function() { alert("Hi!"); })
    

    Note that the last example involves parentheses - that's commonly done to "defuse" the "Oh look a function declaration!" behavior of the parser. That opening parenthesis means that the function keyword does not appear at the absolute beginning of the statement, so it's therefore just a function instantiation expression.

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