Javascript pattern: isolate init code
Wednesday, August 5, 2009 6:28:17 AM
Last few weeks, I have been wading through lots of Javascript code, bugs have a tendency to force you to do things that you would normally not want to do. I have seen a lot of bad code, and some good. And, guess what, I still like Javascript a lot, in fact, I like it even more.
A common pattern found on pages on the Internet is using an anonymous function to encapsulate initialization code from polluting the global scope.
In Javascript, the scope of local variables is a function, not a block, as it is in many other popular languages. This is why you would like to use a function for encapsulation.
If you declare an anonymous function, and call it at the same time, it is approximately the same thing as an anonymous block in C++.
(function () {
function printToScreen(str) {
document.write("<p>" + str);
}
var s = "Hello world";
printToScreen(s);
})();
// Here, s is not "Hello world", and printToScreen is not available.
You put the anonymous function inside parentheses, otherwise you will not be able to call it (because of Javascript's syntax). Then you call the function by adding (). In Javascript, you always have to add parentheses, since otherwise it is just a function reference, not a function call.
I always try to remember to add ; at the end of each statement. You do not have to do that always, ; is optional in a lot of places. The optional use of ; is one of the worst design mistakes in Javascript. The rules for when you are allowed to omit ; is too complex for most people to remember.
In my opinion, calling an anonymous function directly when it is declared has a quite ugly syntax. I think it is hard to read. If you want to spot if a file is using an anonymous function to encapsulate initialization code, look for the pattern "(function (" at the start of a line. If you match that pattern, it is almost certain that this is encapsulated initialization code. I think I would like to have some sort of support from my text editor for this kind of construct. (color coding or something similar)







