10
votes
\$\begingroup\$

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:

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?

\$\endgroup\$
7
votes
\$\begingroup\$

I would recommend you use a closure like this:

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.

\$\endgroup\$
4
  • \$\begingroup\$ Looks less organised, but surely has its advantages. \$\endgroup\$
    – pimvdb
    Feb 25 '11 at 6:39
  • \$\begingroup\$ @pimvdb - How so? One would think that allowing extra protection for your private state qualifies as improving organization. \$\endgroup\$ Feb 25 '11 at 16:40
  • \$\begingroup\$ That's true, but just defining a module as var someModule = { ... } is clearer in my opinion. Nevertheless, I'm going to use the closure way - thanks. \$\endgroup\$
    – pimvdb
    Feb 25 '11 at 19:55
  • \$\begingroup\$ @pimvdb - Oh I see, you are thinking more in terms of clarity rather than a literal interpretation of organized. \$\endgroup\$ Feb 25 '11 at 19:58
1
vote
\$\begingroup\$

I chose for the closures: http://jsfiddle.net/raXQT/4/.

Now it's possible to safely and more easily access variables. Also I love the fact that Chrome supports JavaScript getters and setters like this (it's going to be Chrome-only anyway).

var t=(function() {
    var a = 0;
    return {
        get val() {
            return a;
        },
        set val(v) {
            a = v;
        },
        alertA: function() {
            window.alert("alertA() shows a: " + a);
        }
    }
})();

alert("t.val: " + t.val);
t.val = 2;
alert("t.val = 2\n\nt.val: " + t.val);
t.alertA();
t.a = 6;
alert("t.a = 6\n\nt.val: " + t.val);
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.