The Wayback Machine - https://web.archive.org/web/20110321082655/http://answers.oreilly.com:80/topic/787-how-to-use-an-own-namespace-for-variables-in-javascript/

Jump to content

How to use an own namespace for variables in Javascript?

horshack's Photo
Posted Nov 26 2009 04:39 PM
3941 Views

I have to join a few home-made Javascript-libraries together. It's so easy to use global variable-names, but how can I stay in my own namespace like "mycompany.strings"?

Tags:
2 Subscribe


1 Reply

0
  KBenson's Photo
Posted Nov 29 2009 10:28 PM

Since these are home-made javascript libraries, this isn't too hard.

You can assign an object to a variable, and combine your libraries within this object. You can repeat the process within the object to achieve multiple levels as well.

e.g.

var mycompany = {
'utilities': {
'removeEmail': function(string) {
// Code to remove all email addresses
return newString;
},
},
'display': {
'defaultSize: [100, 100],
'showBox': function(x, y, sizex, sizey) {
// do some stuff create stylized div for box, etc.
return boxDivElement;
},
},
'var1': 'foo is at foo@bar.com',
'func1': function() { return 'bar is at bar@foo.com'; }
}

// Example usage
var myString1 = mycompany.var1;
var myString2 = mycompany.func1();
var someFunction = mycompany.func1;
var myString3 = someFunction(); // myString3 == mySting2;
var parsedString = mycompany.utilities.removeEmail(mystring1);
var divBox = mycompany.display.showBox(400, 500, 200, 300);
divBox.innerHTML = parsedString;


Now, I haven't actually tested the above code, so there may be numerous errors, and even some basic JS logic problems as it's been a little while since I wrote any functional JS, but the general theory is sound.

P.S. there's more complex and complete ways to get namespaces in JS, but this should suffice for combining a few home-made libraries.

close