What's the difference between function(){}() and !function(){}()

Possible Duplicate:
!function(){ }() vs (function(){ })()

So I was just reading through the source of the new Bootstrap (2.0) from Twitter and noticed that there is an exclamation mark before the self-invoking anonymous function. When I saw this I immediately thought "Oh crap, there's a new, better way to do this?".

See for yourself!

  • http://markdotto.com/bs2/js/bootstrap-modal.js
  • http://markdotto.com/bs2/js/bootstrap-dropdown.js
  • http://markdotto.com/bs2/js/bootstrap-scrollspy.js
  • http://markdotto.com/bs2/js/bootstrap-popover.js
  • http://markdotto.com/bs2/js/bootstrap-tooltip.js
  • http://markdotto.com/bs2/js/bootstrap-tab.js
  • Anyways, what's the difference? There must be a reason for it because they use it consistently in all of their JavaScript plugins (for Bootstrap).

    Another thing I noticed was the "use strict" right after this. I don't think it's related to my previous inquiry, but can anyone explain this?

    Thanks!


    function(){} ();
    

    By itself (see Point's comment) isn't going to be valid, since

    function() {}
    

    is a function declaration. To invoke it immediately, you need to get the JavaScript engine to treat the function as an expression. People usually do this as either of

    (function(){}) ();  //more common
    
    (function(){} ()); // Papa Crockford's preference:
    

    with

    !function(){}();
    

    simply being a shorthand version of the same thing.


    If you have 2 scripts:

    script1.js :

    (function(){
    
    })()
    

    script2.js :

    (function(){
    
    })()
    

    And you concatenate them, you get:

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

    This causes an error, while:

    !function(){
    
    }()
    !function(){
    
    }()
    

    Doesn't.


    The ECMAScript Language Specification, section 12.4, says:

    An ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration.

    So if you want an expression statement that executes an anonymous function, you have to work around this restriction. Adding a ! (which just negates the result of the function) makes it clear to the interpreter that it's not a function declaration, avoiding this ambiguity.

    链接地址: http://www.djcxy.com/p/96900.html

    上一篇: 否定自我调用功能? !函数($){...}(window.jQuery);

    下一篇: function(){}()和!function(){}()之间有什么区别?