Recently I was reading someone else’s code, and came across this:
// Semicolon (;) to ensure closing of earlier scripting
// Encapsulation
// $ is assigned to jQuery
;(function($) {
// DOM Ready
$(function() {
...
});
})(jQuery);
I understand the point of the leading ;, And I understand that $(function() { is the same as document ready, but what is the point of adding function($)?
I understand it’s a closure, but since this is always being called at the global scope, it seems like you don’t need to bother with it. The $(function() { will use the same global object either way, no?
Is it to safeguard against something, or is it a best practice for another reason?
It’s a common structure for a jQuery plugin. It safeguards against the
$identifier having been overwritten and used for something else. Inside the anonymous function,$is always going to refer to jQuery.Example:
By introducing a new scope, you can ensure that
$refers to what you expect it to:The main reasoning behind this is that numerous other JavaScript libraries use
$as an identifier (e.g. PrototypeJS). If you wanted to use both Prototype and jQuery, you need to let Prototype have its$identifier, but you probably don’t want to write outjQueryevery time you want to call a jQuery method. By introducing a new scope you allow jQuery to have its$back in that execution context.