jQuery Plugin Pattern & self-invoking javascript function

Neeraj Singh

By Neeraj Singh

on March 13, 2009

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.

Here is a great article which describes in detail how to wrap your javascript code inside a jQuery plugin. The article did a great job of explaining the basics however it took me a while to understand the self-invoking functions.

Self-invoking functions

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:

1function hello() {
2  alert("Hello");
3}
4var hello = function () {
5  alert("Hello");
6};

The end result in the above two javascript statement was same. In the end a variable named hello was created which is a function.

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

1var hello = function () {
2  alert("Hello");
3};
4hello();

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

1// original
2function hello() {
3  alert("Hello");
4}
5
6// step1 wrap everything in () so that we have a context to invoke
7(function hello() {
8  alert("Hello");
9})(
10  // now call () to invoke this function
11  function hello() {
12    alert("Hello");
13  }
14)();

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

1(function ($) {
2  // ....
3})(jQuery);

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 parameter is $. $ is nothing else but jQuery object that is being passed while invoking this function.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.