I've seen code like this everywhere, and maybe you have too. A function (hopefully wrapped in parenthesis) followed by some variables in parenthesis.
(function(a, $){
... code ...
})(window, jQuery);
I eventually started trying to research what they were, how they worked, and why they should be used. Most of the explanations got thick quick, so I thought I'd simplify things.
In essence, this is declaring and calling a function all at the same time. The easiest way to think of it (for me, anyway) is that this:
(function(a, $){
... code ...
})(window, jQuery);
...is roughly equivalent to this:
var myFunction = function(window, $){
... code ...
}
myFunction(window, jQuery);
There are some (pretty big) differences (such as when and how it runs), but this is enough to get you started.
The parenthesis wrapping the function aren't required, but are considered best practice and common courtesy because they help to identify this function as self-executing, and making it easier to find the parameters being passed in.
Without getting too deep into it, these functions are really nice for compartmentalizing code (restricting access and preventing conflicts), as well as making your code more compressible. Hopefully some day when I have the time (and more understanding), I can write about this some more, but for now I wanted to share this little tidbit that has helped me understand what was going on here.
Comments
Post a Comment