A common problem when coding very large Javascript applications is that the global namespace gets polluted, which causes the programmer to name their functions and variables something they don’t want to name them (just for the sake of uniqueness). If Javascript had namespacing and classes, we wouldn’t have this problem. Good news, there is a solution to allow for classes and namespacing it goes a little like this:
var az = function() { var variable1 = "test"; var variable2 = "test2"; function testFunc() { alert(variable1); } return { init : function() { testFunc(); this.testFunc2(); }, testFunc2 : function() { alert(variable2); } }; }(); az.init();
Let’s take a look at this in more detail!
You’ll notice that we have variable1 and variable2. These variables can be thought of as private variables. Additionally, testFunc can be thought of as a private function.
Any of the code that lives within the return block can be thought of as public. These are the only functions that may be called externally. If you are calling a public function within the class, you must either put the full path to it (ex: az.testFunc2()) or prepend it with this (ex: this.testFunc2()).
So now you have a good example of how to represent a class in Javascript. But let’s take this a step further and emulate namespacing as well.
Let’s say we had the code above in addition to this code below:
var az.util = function() { return { gebi : function(obj) { return document.getElementById(obj); } }; }();
Now we can call az.util.gebi('id_to_get_element_of').
You can keep adding level after level to the namespacing so that you might have something like az.util.date.convert.toSql().
Using this technique is great because you do not junk up your global namespace and you can organize your code very well. In fact, each different “class” can live in its own file and you can create a mechanism to import the files as you need them (dramatically improving load time).
An interesting note: You may notice on the examples that there is not a line break between return and the opening brace. Adding a line break will cause the code to break (who knows why?!). Therefore, you will have to keep the opening brace on the same line as the return.
