I wish to make my javascript more more modular by splitting it up into different files and giving each file a 'sub' namespace like so.
subA.js
if(typeof ex == "undefined") {
var ex = {};
}
ex.subA = function() {
//all functions of subA here
}
And same for subB etc.
At the moment I have 1 file, ex.js
var ex = (function() {
//private vars/funcs
return {
//public vars/funcs
}
})();
It looks like I should move most of my functions to subA.js and subB.js but still include ex.js at the start, with subA.js and subB.js afterwards.
I have a number of questions.
I'm having a hard time remembering how I made the initial namespacing file, ex.js. It looks like the anonymous function is there to make everything private initially, but I can't remember why it needs to be enclosed in parentheses and then executed straight away with the
();
at the end.Following on from q1, should my sub files be in the same format as ex.js, ie, have the anon function wrapped in parentheses and executed straight away?
It looks like the sub files will only have access to the public functions of
ex
, is this true? If it is, how can I allow my sub files access to the private functions as well?In my HTML file, in my document.ready function (jQuery), should I be initialising ex to a variable or can I call each function individually by going
$(document).ready(function() { ex.doSomething(); ex.doSomethingElse(); }
Is there a difference between the two? I think that when ex.js is included, a global variable ex is created straight away (due to the anonymous function being executed straight away), so I shouldn't need to redefine it in document.ready.
Is the first if statement in subA.js any different from
var ex = ex || {};
Which is better?What js code style standards do you use?
If you read through all this you already deserve an upvote, cheers.