I am just starting out with writing jQuery plugins. I wrote three small plugins but I have been simply copying the line into all my plugins without actually knowing what it
Actually, this example helped me to understand what does (function($) {})(jQuery);
mean.
Consider this:
// Clousure declaration (aka anonymous function)
var f = function(x) { return x*x; };
// And use of it
console.log( f(2) ); // Gives: 4
// An inline version (immediately invoked)
console.log( (function(x) { return x*x; })(2) ); // Gives: 4
And now consider this:
jQuery
is a variable holding jQuery object.$
is a variable
name like any other (a
, $b
, a$b
etc.) and it doesn't have any
special meaning like in PHP.Knowing that we can take another look at our example:
var $f = function($) { return $*$; };
var jQuery = 2;
console.log( $f(jQuery) ); // Gives: 4
// An inline version (immediately invoked)
console.log( (function($) { return $*$; })(jQuery) ); // Gives: 4