Location of parenthesis for auto-executing anonymous JavaScript functions?

前端 未结 4 1990
离开以前
离开以前 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:17

    They're virtually the same.

    The first wraps parentheses around a function to make it a valid expression and invokes it. The result of the expression is undefined.

    The second executes the function and the parentheses around the automatic invocation make it a valid expression. It also evaluates to undefined.

    I don't think there's a "right" way of doing it, since the result of the expression is the same.

    > function(){}()
    SyntaxError: Unexpected token (
    > (function(){})()
    undefined
    > (function(){return 'foo'})()
    "foo"
    > (function(){ return 'foo'}())
    "foo"
    

提交回复
热议问题