What makes the anonymous function is that it has no name :) See:
(function ( $ ) {
Where is the name? It does not, so it's an anonymous function. The parentheses in the loop are required by a syntax detail (if the line starts with function
, the function must have a name). More details on this in this other question: What is the difference between the functions var name = function () and function name ()?
The reasons for the plugin to be inside the anonymous function:
All variables you create, with var
, within the anonymous function will not be available globally. That's fine, your plugin's code gets encapsulated and you do not risk interfering with other scripts on the page.
The anonymous function is immediately invoked (note ( jQuery )
) at the end), and receives as argument the jQuery
object. Only within the function this object is available as $
. Thus, your plugin may refer to or jQuery as $
without running the risk of referring to another library that also uses the $
identifier - for example, prototype .