Let's break this down:
(function($) { /* Code here */ })(jQuery);
First, the construct:
(function() {})();
creates an immediately executed function expression (often called IIFE). This is a function that is executed immediately rather than defined now, but called later. It is essentially an anonymous (unnamed) function that is defined and then executed right away.
Then, passing jQuery to it like this:
(function() {})(jQuery);
passes jQuery as the first argument to that immediately executed function. Then, naming that first argument as $
defines that symbol inside the function to correspond to the first argument that is passed.
(function($) {})(jQuery);
which in expanded form looks like this:
(function($) {
// you can use $ here to refer to jQuery
})(jQuery);
There a couple nice thing about this for jQuery plugin authors:
The IIFE creates a local function context so you can have variables which are "global" for your plug-in, but are not actually global variables and thus don't pollute or conflict with the actual global variable namespace.
You can program with $
for jQuery, whether or not the host program actually has that defined for jQuery because you've defined $
locally within your function.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…