问题
I'm working with a script and have found the following, which I really can't find any info of what it means
(function($) {
$(document).ready(function(e) {
... bla bla bla ...
});
}) (jQuery);
Is (function($){}) (jQuery);
the same as $(function () {});
? and if so, why would somebody define twice document.ready
?
回答1:
No, it's not the same. It's an anonymous function which is being passed the jQuery object, to insure that it is available as the local variable $
within the scope of the function, even if the global variable $
is overwritten by another library. It is completely different than $(function () { })
and $(document).ready(function () { })
.
This particular pattern is recommended in the jQuery plugin authoring documentation:
[When authoring a plugin] it's a best practice to pass jQuery to an IIFE (Immediately Invoked Function Expression) that maps it to the dollar sign so it can't be overwritten by another library in the scope of its execution.
(function( $ ) { $.fn.myPlugin = function() { // Do your awesome plugin stuff here }; })( jQuery );
回答2:
Is
(function($){}) (jQuery);
the same as$(function () {});
?
No. The first is immediate invocation of an anonymous function, used primarily for preventing pollution of the global scope. In this case, it's also used to make sure that $
is a reference to jQuery
, without worrying about overwriting $
elsewhere.
The second is the shorthand for binding a document ready handler with jQuery.
More reading:
- What is the purpose of a self executing function in javascript?
- What is the reason for this JavaScript immediate invocation pattern?
回答3:
No it isn't, (function($){}) (jQuery);
is an IIFE(Immediately invoked function expression) passing jQuery as a parameter and using $
to represent it in the function scope so that no conflicts will occur if another library that uses $
is loaded without using jQuery.noConflict.
回答4:
Nope
(function(){})();
is executed as soon as the browser encounters that script. .ready() is an event that is triggered after the entire document is parsed
回答5:
No it's not. It is a closure with a document ready handler inside it. It is used to ensure that the $
within the enclosure is reserved for jQuery and does not interfere with any other library.
回答6:
A nice clear explanation here;
http://jquery-howto.blogspot.com/2008/12/what-heck-is-function-jquery.html
来源:https://stackoverflow.com/questions/14362153/is-this-a-double-document-ready