JavaScript flexibility
In JS you have the natural flexibility to extend an object you have previously declared. Even more you can extend any native objects! That makes the writing of a jQuery, or whatever javascript library, plugins to be very easy.
As you may know in JS you can have object declared like that:
var obj = { a : 1, b : 2 };
That is an object with two properties a and b which values are respectively 1 and 2. If you’d like to extend this object later you can just write:
obj.c = 3
and now the object looks like that:
{ a : 1, b : 2, c : 3 }
That’s perfect when you’d like to write plugins to jQuery.
As you may know the $ sign in jQuery is synonym of the function called jQuery, so you can add any property to that library with just writing:
jQuery.myMethod = function() {}
JS closures
What are closures? Well you know in almost every programming language you’ve scope of the variables. In JavaScript instead if you declare a variable on the global level:
var a = 1;
you can access this variable right from everywhere! That’s not good at all. If you later declare a function and there you initialize a variable with the same name – the scope of the variables make visible and useful only the inner variable declared within the function.
This helps the programmers to force the usage of pseudo private properties of an object.
The technique is quite simple. You make a anonymous function:
(function() {})();
and every variable inside is not visible outside. Thus you can export only specific features using both the window object or parameters:
var externalObject = {};
(function(o) { var myObject = { a : 1, b : 2} o.a = myObject.a; })(externalObject);
Thus you export only one of the properties of myObject. Instead without the closure both a and b properties would be visible to the world.
In help comes also the fact that this anonymous functions are “self-called” so you don’t have to call them after the declaration.
Legacy code and good practices
To come back on the jQuery plugins – it’s good practice to make your plugins in closures so they should not interfere with other code written before.
And one more time – use the jQuery object for your plugins instead of the $ sign, because some libraries different from jQuery use this sign globally and you can have problems with that.
In my next post I’ll write a simple plugin so you could see how it can be done with very small code chunk.