what is the meaning of "!function($){}(window.jQuery)"?
Possible Duplicate:
What does the exclamation mark do before the function?
What does !function ($) { $(function(){ }) }(window.jQuery) do?
what is the meaning of "!function($){}(window.jQuery)" ?
<script type="text/javascript">
!function($){
//some codes here
}(window.jQuery)
</script>
this js orginal code url:http://twitter.github.com/bootstrap/assets/js/bootstrap-dropdown.js
The !
at the beginning of the line turns your function into a function expression, it has the basically same effect¹ as the more popular IIFE forms:
(function($){}(window.jQuery));
//which in turn is the same as
(function($){})(window.jQuery);
Then it is immediately invoked by passing window.jQuery
as the $
argument. This is useful to be able to use $
referencing jQuery inside the function independently of the page having jQuery in noConflict
mode or not.
This approach is very common (and recommended) when developing plugins for 3rd-party use.
Little more explained: Function declarations can't be part of an expression, hence when you put the function keyword inside a ()
or precede it with a unary operator, it is interpreted as a function expression.
¹ There is a subtle difference between (function(){}())
and !function(){}()
: while the parentheses simply evaluate the function to a function object in the form of a function expression, the unary !
will do the same thing and flip the return value of the function expression. As you're not assigning this value to anything, it will simply be discarded.
It is 1 byte in load time vs the cost of a !
operation in execution time. Both of these shouldn't take more than a fraction of milli/microsecond. It is mostly a matter of coding style preference.