I understand JavaScript closures, and I\'ve seen this done in native JS:
(function () {
// all JS code here
})();
But, what does adding t
(function() {
// all JS code here
})();
Is an Immediately-Invoked Function Expression (IIFE), pronounced "iffy". Some people also call them "anonymous, self-executing functions", or just "self-executing functions".
(function(aParameter) {
alert(aParameter); // will alert "an argument"
})("an argument");
Here's an IIFE which takes the parameter 'aParameter' and passes itself the argument "an argument".
(function($){
alert($(window).jquery); // alert the version of jQuery
})(jQuery);
This one is similar, but "jQuery" (THE jQuery object instance) is the argument to the IIFE, and in this case, jQuery gets passed as the '$' parameter. In this way, simply by typing '$', the body of the IIFE has access to jQuery and its members. This is a common jQuery convention, and it's common for people writing jQuery plugins to maintain this convention in this way.
Not only does the above code maintain the jQuery convention, it also ensures that neither you nor anyone else can accidentally break that convention. E.g., take the following code:
var $ = function() {
alert('foo');
}
This code turns '$' into something which is definitely not jQuery. If someone did this in some other code outside your plugin code, and then you didn't explicitly pass jQuery as '$' to your plugin, then you wouldn't be able to use '$' as jQuery like you usually do.