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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With