Location of parenthesis for auto-executing anonymous JavaScript functions?

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

    The difference just exist because Douglas Crockford doesn't like the first style for IIFEs! (seriuosly) As you can see in this video!!.

    The only reason for the existence of the extra wrapping () {in both styles} is to help make that section of code Function Expression, because Function Declaration cannot be immediately called. Some scripts / minify-ers just use +, !, - & ~ instead of too parentheses. Like this:

    +function() {  
        var foo = 'bar';  
    }();
    
    !function() {  
        var foo = 'bar';  
    }();
    
    -function() {  
        var foo = 'bar';  
    }();
    
    ~function() {  
        var foo = 'bar';  
    }();
    

    And all these are exactly the same as your alternatives. Choosing among these cases is completely on your own & makes no difference. { The ones with () produce 1 Byte larger File ;-) }

提交回复
热议问题