netrenaissance.net

this.code();

So as mentioned in my last post, I've been reading about some awesome javascripty stuff lately, and I came to what I believe is a fairly good analogy between statically-typed land and javascript global variable/scoping issues.

Many people wonder why it is that you should scope your functions in such a way as to minimize your global variable footprint. To recap: when you define a function in javascript, generally it is lexically scoped, which means that if you do not attach your function to an existing object, your function is defined in the global scope.


function myAnnoyingFunction(someOperand){
  alert('I am annoyingly adding myself to the global scope');
}

What this means is that your function is now there, sitting in the global scope with all the other javascript fragments your end consumer may have running there as well. This is bad for a variety of reasons including but not limited to: possible interference with other javascript code, security implications for your code and generally being sloppy.

Here is my statically typed analogy: Every time you define a globally scoped variable, you are effectively creating a new namespace declaration in your assembly.

Nobody likes that kid.

You know the one, you import their assembly and you get namespaces like "Random_Junk.MyClass1" and "Vendor.MyClass" and there is no intellisense defined for them, and it just makes you want to scream.

"This is not the way to define a publicly accessible API!" you mumble to yourself... forcefully... with vehemence.

In any case, don't do it. If you are worried about your javascript, or aren't very good at determining your scope, check out the JSLint tool, it will warn you about this sort of antisocial behavior.

In other news, there is a great coding convention for jQuery which involves starting your files with a semicolon. I highly recommend people get into this habit, as it protects you from a variety of nastiness which can happen if the server or your end users concatenate javascript files together for their clients.