patternjavascriptMinor
Separating and organising modules with objects?
Viewed 0 times
modulesobjectswithandorganisingseparating
Problem
As I'm creating a 3D Tic-Tac-Toe game, I'm having several modules inside my JavaScript application. For example, there is a 3D module which handles perspective calculations, whereas a Multiplayer module manages everything with relation to online playing.
Is it good practice to put functions of each module in its separate object?
I currently have:
multiplayer.js:
renderer.js:
and so on.
Is this a good practice of organising my project? Or is there a more efficient way?
Is it good practice to put functions of each module in its separate object?
I currently have:
multiplayer.js:
var Multiplayer = {
socket: new Socket("ws://192.168.0.100:123/test"), // Relevant variables concerning multiplayer stuff
createSession:
function() {
//...
}
}renderer.js:
var Renderer = {
f: 200, // Relevant variables concerning 3D rendering stuff
g: 200;
render:
function() {
//...
}
}and so on.
Is this a good practice of organising my project? Or is there a more efficient way?
Solution
I would recommend you use a closure like this:
The biggest reason why this is a good idea is that it adds the ability to keep private state within the closure. Normally you can define private properties by convention but as the complexity of an object increases the better it is to keep certain things private.
var Obj = (function() {
var privateState = null;
return {
A: 1,
B: true,
C: function() {
return privateState;
}
};
})();The biggest reason why this is a good idea is that it adds the ability to keep private state within the closure. Normally you can define private properties by convention but as the complexity of an object increases the better it is to keep certain things private.
Code Snippets
var Obj = (function() {
var privateState = null;
return {
A: 1,
B: true,
C: function() {
return privateState;
}
};
})();Context
StackExchange Code Review Q#975, answer score: 7
Revisions (0)
No revisions yet.