I was looking at the jQuery plugins for Twitter Bootstrap and saw that they were all defined using a pattern like this:
!function($) {
// code here
// plugin definition here
} ( window.jQuery || window.ender);
This looks like a variation of the immediately executing anonymous function (anonymous closure):
(function($) {
// code here
}(jQuery));
Can someone explain what the Bootstrap variation does and why? Is this a better way to write an anonymous closure?
Thanks!
I was looking at the jQuery plugins for Twitter Bootstrap and saw that they were all defined using a pattern like this:
!function($) {
// code here
// plugin definition here
} ( window.jQuery || window.ender);
This looks like a variation of the immediately executing anonymous function (anonymous closure):
(function($) {
// code here
}(jQuery));
Can someone explain what the Bootstrap variation does and why? Is this a better way to write an anonymous closure?
Thanks!
Share Improve this question asked Jan 20, 2012 at 23:30 PeterPeter 12.7k3 gold badges36 silver badges39 bronze badges 4- 1 I think the only difference is that it saves you a character... Oh, and makes the pattern obscure. – Jordão Commented Jan 20, 2012 at 23:33
-
2
@Jordão: Avoiding the
()
helps avoid bugs like this one – user1106925 Commented Jan 20, 2012 at 23:42 - @am not i am: thanks for pointing that out. I'd still not use this idiom though, as it's not the proper way to fix that kind of bug. – Jordão Commented Jan 21, 2012 at 1:23
-
@Jordão: I wouldn't call it an improper fix. Irrespective of the bug, I still don't use
()
to create an IIFE. The bug is a bination of JS only having function scope, having ASI, and overloading the()
syntax. It's up to the individual developer as to how they want to deal with it. Inserting a semi-colon is one option. – user1106925 Commented Jan 21, 2012 at 2:21
1 Answer
Reset to default 11// |---1. makes the function as part of an expression
// | so it can be immediately invoked
// v
!function($) {
// ^
// |___4. references what was passed, window.jQuery or window.ender
// code here
// plugin definition here
} ( window.jQuery || window.ender); // <---2. immediately invoke the function
// ^ ^
// |________________|_______3. pass window.jQuery if it exists,
// otherwise window.ender