I'm writing my first JavaScript application (no 3rd party libraries used) and looking for some high-level guidance on how to better organize the code into separate classes & files.
Here is a simplified/contrived example to illustrate my current organizational layout/problems:
game.js:
/* Lots of constants, enums, etc defined here.
Can't define them inside Game function as
they are used by Graphics and ui_player classes too.
*/
function Game(ui) {
/* Lots of things defined here which are exclusive to Game class. */
var graphics = new Graphics();
graphics.load();
ui.setCanvas(graphics.canvas);
this.start = function() {
mainLoop();
};
function mainLoop() {
/* ... */
ui.player.updateAbc(abc);
/* ... */
paint();
}
function paint() {
graphics.renderAll()
}
/* ... */
}
graphics.js:
function Graphics() {
/* Some constants defined here that are exclusive to Graphics class. */
var canvas = this.canvas = ...;
var ctx = canvas.getContext("2d");
/* ... */
this.renderAll = function() {
ctx.drawImage(...);
};
/* ... */
}
ui.js:
/* Lots of constants related to UI classes here. */
function ui() {
var div = this.div = ...;
var canvas;
/* ... */
var player = this.player = new ui_player();
div.appendChild(player.div);
this.setCanvas(c) {
if (canvas)
div.removeChild(canvas);
canvas = c;
div.appendChild(canvas);
};
/* ... */
}
ui_player.js:
function ui_player() {
var div = this.div = ...;
/* ... */
this.updateAbc = function(abc) {
div.innerHTML = abc;
};
}
main.js:
ui = new ui();
game = new Game(ui);
game.start();
What I dislike about this:
- I feel that my scopes are clumsy.
- I dislike the fact that I have constants in global scope because they are shared across multiple classes.
- I dislike the fact that I have to pass ui to Game and then to Graphics, but I'm not sure if this is bad or if allowing every class to access others would be worse.
How can I improve my code structure? How can/should I put it all into a namespace hierarchy where classes can access classes above (and maybe even below) them?
P.S. - I'm compiling with Google Closure Compiler (advanced) if that makes any difference. No 3rd party libraries are used.