What is the difference between these 2 JavaScript declarations?

后端 未结 5 1362
执念已碎
执念已碎 2021-01-02 05:10

For one of them the \"()\" is inside, for the other one it is outside. Here they are:

var a = (function() {
    return {
        bla: function(         


        
5条回答
  •  被撕碎了的回忆
    2021-01-02 05:46

    There is no difference.

    The [unnecessary] parenthesis are just in different places. The function declaration is already an expression due to where it is located. The parenthesis would make a difference, while still resulting in equivalent code, if the declaration was in a statement context (and ironically they would turn it back into an expression context), which it is not.


    The common use of parenthesis in a similar scenario is for self-invoking functions. The parenthesis are required in this case because

    function x () { alert("hi!") } ()
    

    is parsed as

    function x () { alert("hi!") }; ()
    

    when it appears as a statement -- or "top level element of a block" -- where it is parsed as a "FunctionDeclaration". Thus the following form is often used:

    (function () { alert("hi!") })()
    

    This works because function ... is no longer a statement, as above, but an expression (parsed as a "FunctionExpression"), and the expression can continue so the Automatic Semicolon Insertion does not occur as in the previous case. Also note that the function name can be omitted.

    However, because in the post the function ... appears in an on the right of an = (in an "AssignmentExpression") it is therefore already in an expression context (is parsed as a "FunctionExpression") and thus no additional parenthesis are needed.

    All of these are identical, but I prefer the 2nd form (for consistency within my code):

    a = function () {} ()
    b = (function () {}) ()
    c = (function () {} ())
    

    Happy coding.

提交回复
热议问题