Jump to content

How to use an own namespace for variables in Javascript?

horshack's Photo
Posted Nov 26 2009 04:39 PM
14679 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


2 Replies

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.
+ 2
  Rick001's Photo
Posted Nov 05 2012 10:33 AM

this post is a few years old, but i wanted to put forth another idea as to how to approach namespacing some existing code. it appears to me that the closure pattern would fit this need quite nicely. For example, see this typical bit of code, note the variable is in the global namespace as is the function:

var vehicle = {color:'red',type:'truck'}

function changeVehicleColor(str){
vehicle.color = str;
}

With the closure pattern all that you would need to do is to wrap the above code within the closure construct, like so:

var myCompany = (function(){

var vehicle = {color:'red',type:'truck'}

function changeVehicleColor(str){
vehicle.color = str;
}

})();

Now the "vehicle" variable and the "changeVehicleColor" function are wrapped within the "myCompany" object. At this point they are private - they're not accessible, so you have to expose a way of accessing them. You can do this with a return statement, see below:

var myCompany = (function(){

var vehicle = {color:'red',type:'truck'}

function changeVehicleColor(str){
vehicle.color = str;
}

return {
changeVehicleColor:changeVehicleColor
}

})();

The "changeVehicleColor" method is now exposed for use while the "vehicle " variable is still private. To change the vehicle color you would do the following:

myCompany.changeVehicleColor('yellow');

All done. The nice thing here is that you're just wrapping the existing code within the closure construct. A lot easier than the original example, IMO, where you are creating an object literal and modifying the original code to do so. Not ideal for what the op claims are "a couple of libraries". You can avoid that effort with a closure. The bonus is the notion of private and public bits of the existing code. The original sample, while it does work, leaves all variables open for manipulation outside of the namespace (see the "var1" example).

In addition, you can easily build upon the myCompany object. For example, if you have some utility methods, you could wrap them separately but within the same namespace like so - note that the "myCompany" namespace has already been created, so I am not using the var keyword (btw, this would also be true of the first answer):

myCompany.utils = (function(){
// your code here
return{
// your methods, getters/setters here
}
})();


Thus, you can break the library into different physical files if you like as long as the one that creates the namespace (var myCompany...) is the first file to load.

There you go... its up to the reader to decide which approach is the best for their particular application.