I’ve been writing a lot more Javascript recently, and have occasionally run into variable and function naming conflicts, where I pick a name, not realizing that some other Javascript library that I’m using already has a function or variable with that name. This leads to a lot of troublesome, unnecessary debugging.
For a while, I used the old-fashioned technique of prefacing all my variable and function names with something fairly unique, like my initials. So instead of a variable named “i” I would have “mdf_i”. Messy, and ugly, and more than half the time I would forget to do it.
Doing a Google search for “javascript namespace” brought back quite a few results of the type:
After looking through the suggestions, I’ve started using Dustin Diaz’s solution. Here’s a quick example script I put together that shows how it works, using a new object “mdf” that contains all my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | var mdf = function() { // This can be accessed only from methods inside mdf var vtest1 = 'vtest1'; // This can be accessed only from methods inside mdf function ftest1() { alert('inside ftest1'); } // Public methods are part of the returned object: return { // mdf.ftest2() can be accessed from the main javascript // scope or from another mdf method ftest2 : function() { alert('inside ftest2'); }, // To execute a public method of mdf, specify the mdf object ftest3 : function() { mdf.ftest2(); }, // To access a private function or variable, use it normally ftest4 : function() { ftest1(); alert(vtest1); } }; }(); alert(vtest1); // This will fail ftest1(); // This will fail mdf.ftest4(); // This will succeed |
sungo
November 16, 2007You might want to take a look at http://openjsan.org/ . It was built by perl programmers who wanted some of perl’s goodness in javascript, specificlaly packages and namespaces.