|
|
|||
How to use an own namespace for variables in Javascript?
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"?
1 Reply
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. |
|||
|