Lzhelenin Lzhelenin - 4 months ago 16
Javascript Question

js - avoiding namespace conflict

Thus far I've worked only with relatively small projects (and mostly alone), but this time I have to collaborate with other programmers... basically because of that I must plan the structure of the website very carefully for the avoidance of spending hours debugging the code.

At this point I suppose doing that in the following manner. I divide my code in modules and store each module in a separate file inside an object (or a function) with a made-up name (lzheA, lzheB, lzheC etc.) to avoid conflicts whether an object with the same name was used in an another piece of code. When the document is loaded, I declare a variable (an object) that I use as a main namespace of the application. Properties of the object are the modules I defined before.

// file BI.lib.js
var lzheA = {
foo: function() {

},
bar: function() {

},
}

// file BI.init.js
function lzheK() {
BI.loadPage();
}

// file BI.loadPage.js
function lzheC() {
var result = document.getElementById('result');
result.innerHTML = "that worked";
}

// and so on
var lzheA,lzheB,lzheD,lzheE,lzheF,lzheG,lzheH,lzheI,lzheJ;

// doing the following when the document is loaded
var BI = {
lib: lzheA,
menu: lzheB,
loadPage: lzheC,
customScripts: lzheD,
_index: lzheE,
_briefs: lzheF,
_shop: lzheG,
_cases: lzheH,
_blog: lzheI,
_contacts: lzheJ,
init: lzheK,
}

BI.init();


https://jsfiddle.net/vwc2og57/2/

The question... is this way of structuring worth living or did I miss something because of lack of experience? Would the made-up names of the modules confuse you regardless of the fact that each one used only twice - while declaring the variable and assigning it to a property?

Answer

I consider the namespaces a good option when you want to modularize applications in Javascript. But I declare them in a different way

var myModule = myModule || {}; // This will allow to use the module in other places, declaring more than one specificComponent in other js file for example
myModule.specificComponent = (function(){

   // Private things
   var myVar = {};

   var init = function() {
       // Code
   };

   return {
       init: init // Public Stuff
   };

})();

If you want to call the init method, you would call it like this

myModule.specificComponent.init();

With this approach, i guarantee that the module will not be overwritten by another declaration in another place, and also I can declare internal components into my namespaces. Also, the trick of just exposing what you want inside the return block, will make your component safer and you will be encapsulating your code in a pretty way.

Hope it helps

Comments