While reviewing some of the code written in the Twitter Bootstrap Javascript, it looks like they're calling immediately invoked anonymous functions like this:
!function( $ ) { ... }(window.jQuery || window.ender);
Where I've traditionally seen this same thing accomplished this way:
(function($) { ... })(window.jQuery || window.ender);
The first way seems a bit hacky, and I'm not sure if there is any benefit or reason for doing it this way rather than the second way? Note that I understand how it works, I'm looking to understand why they chose that way to do it.
So technically they are both the same. Not major difference between these two declaration. They used based on weather you use JavaScript then you should use $(document). ready declaration in other case you use jQuery library which is a part of JavaScript then you should use $(function) declaration.
In JavaScript, a function allows you to define a block of code, give it a name and then execute it as many times as you want. A JavaScript function can be defined using function keyword.
Difference Between Function and Method:A JavaScript function is a block of code designed to perform a particular task. The javascript method is an object property that has a function value. A function can pass the data that is operated and may return the data. The method operates the data contained in a Class.
Exclamation mark makes any function always return a boolean. The final value is the negation of the value returned by the function.
!
should handle where other JavaScript code is concatenated before this and doesn't have a trailing semi-colon.There is not a huge difference. I would use whatever you were more comfortable with. You should probably toss something at the start of your example to avoid...
var lol = function() { alert(arguments[0]); }
(function() { // Irrelevant. })();
jsFiddle.
Toss in a leading ;
and she works...
jsFiddle.
...or a !
like the Twitter Bootstrap...
jsFiddle.
They're both ways of getting past the ambiguity in the grammar. Neither is more "hacky" than the other. It's just a style choice.
You could also do this:
0 + function( $ ) { // ... } ( window.jQuery || window.ender );
Or:
parseInt(function( $ ) { // ... } ( window.jQuery || window.ender ) );
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