I am learning jQuery and one of things I was struggling with is the plugin pattern. In jQuery world it is very common to wrap the major functionality of the application inside a plugin.
self-invoking functions are anonymous functions declared on run time and then invoke it right then and there. Since they are anonymous functions they can’t be invoked twice. However they are a good candidate for initialization work which is exactly what is happening in the jQuery plugin pattern.
Declaring a function
A function can be declared in two ways:
Please note that in the above case only the functions are declared. They are not invoked. In order to invoke the function we have to do this
How do we invoke an anonymous function. We need to call () on the anonymous function. But before that we need to wrap the whole command in (). Take a look at this
The final result is weird looking code but it works and that is how an anonymous function is declared and invoke on run time.
With this understanding now it becomes easier to see what is happening in this code
In the above case an anonymous function is being created. However unlike my anonymous function this anonymous function take a parameter and the name of this paramter is $. $ is nothing else but jQuery object that is being passed while invoking this function.