(function( $ ){ })( jQuery );
This is a self-signed anonymous function that uses the $ argument in the argument so that you can use it ( $ ) instead of jQuery inside this function and not be afraid to run into other libraries, because in other libraries, $ also has special meaning. This template is especially useful when writing jQuery plugins.
You can also write any character instead of $ :
(function(j){
Here j will automatically catch up with the jQuery specified at the end (jQuery) . Or you can completely exclude the argument, but then you have to use the jQuery keyword around, not $ , without fear of a collision. So, $ enclosed in an argument for short hands, so you can write $ instead of jQuery inside this function.
Even if you look at the jQuery source code, you will see that everything is wrapped between:
(function( window, undefined ) {
This is the same as a self-starting anonymous function with arguments. The window argument (and undefined ) is created and displayed by the global window object at the bottom (window) . This is a popular pattern these days and has a slight increase in speed, because here the window will be studied from the argument, and not from the global window object that is displayed below.
$.fn is a jQuery object in which you create your new function (which is also an object) or the plugin itself, so jQuery wraps your plugin in its $.fn object and makes it available.
Interestingly, I answered a similar question:
JavaScript / jQuery close function syntax
You can also check this article to find out more about the self-contained functions that I wrote:
Javascript Self-Completion Functions
Sarfraz Dec 19 '10 at 17:57 2010-12-19 17:57
source share