Location of parenthesis for auto-executing anonymous JavaScript functions?

前端 未结 4 2072
离开以前
离开以前 2020-11-21 06:57

I was recently comparing the current version of json2.js with the version I had in my project and noticed a difference in how the function expression was created and self ex

4条回答
  •  佛祖请我去吃肉
    2020-11-21 07:08

    There isn't any difference beyond the syntax.

    Regarding your concerns about the second method of doing it:

    Consider:

    (function namedfunc () { ... }())

    namedfunc will still not be in the global scope even though you provided the name. The same goes for anonymous functions. The only way to get it in that scope would be to assign it to a variable inside the parens.

    ((namedfunc = function namedfunc () { ... })())
    

    The outer parens are unnecessary:

    (namedfunc = function namedfunc () { ... })()
    

    But you didn't want that global declaration anyways, did you?

    So it it boils down to:

    (function namedfunc () { ... })()
    

    And you can reduce it even further: the name is unnecessary since it will never be used (unless your function is recursive.. and even then you could use arguments.callee)

    (function () { ... })()
    

    That's the way I think about it (may be incorrect, I haven't read the ECMAScript specification yet). Hope it helps.

提交回复
热议问题