I have got a function, inside which are some simple expressions, adding nums, appending doms, etc.
Since I only have to call it once, so an anonymous function could do it. But which way should I choose and what’s the difference?
1: Shorthand for $(document).ready() {}) I seen this a lot,
$(function(){
var something;
++something;
});
2: Found in jquery plugins. Is it binded to $(document).ready() too?
(function ($) {
var something;
++something;
})(jQuery);
The second one is not bound to the
readyevent.In detail. This:
needs a variable
$defined. Usually this variable exists when jQuery is loaded and points to the jQuery function.Subsequently, when you call the jQuery function with a function argument, jQuery is binding this function argument to the
readyevent. The above is equivalent towhich is in turn a convenience shorthand for
Your second code snippet
does not rely on
$being defined or pointing tojQuery()(this can happen if multiple JS frameworks are loaded in parallel).To still have the convenience of
$within a certain region of code, it creates a function within which$is defined and points tojQuery(). However, it is not bound to a DOM event.But this would be:
This set-up is used to minimize the conflict between JS frameworks or other pieces of code that rely on
$. jQuery plug-in authors use it to write plug-ins that work under many environments.If you think the combined one is too complicated, jQuery also has a shorthand feature, which avoids variable conflicts and binds to
document readyat the same time. But be careful, it only works on jQuery and has some downsides.For more details, see these two articles: