# 2-player board game app

This question is about the best way to declare functions in Javascript. The app is a small 2 player board game I'm working on as part of a bigger web page. Basically I have a socket which receives and send messages and the game acts according to the content of the message.

$(function () { var board = document.getElementById('board'); //When a msg is received //structure of msg : msg = ['action','args'] if (msg[0] === 'action1') { func1(args); } else if (msg[0] === 'action2') { func2(args); } } function func1(args) { var a, b...; doAction1(); //uses the DOM element board, the args and local variables } function func2(args) { var a, b...; doAction2(); }  Now, I was thinking of using an object the way I would do in Java but it seems that it is not the best practice. Should I use a single function like so? $(function () {

var game = function () {
var gamevar1, gamevar2, ...;
action1: function (arg) {
doAction1();
}

action2: function (arg) {
doAction2();
}
}

//when a msg is received [action,param]
game.msg[0](msg[1]);
}

• I just answered, but now I realize I may have misread your code. are the lines with action1 inside of func1() and action2 inside of func2() meant to be method calls? is doAction1 in your second set of code supposed to be the same method? Is the second doAction1 supposed to be doAction2? – Johntron May 17 '13 at 14:52
• Cool, no problem. Was my answer sufficient? – Johntron May 17 '13 at 15:12
• MMM I think so. So the later code would be the best way to do it? – xShirase May 17 '13 at 20:48
• Yeah, isn't it more readable? – Johntron May 17 '13 at 23:48

Since this is all the code you posted, I'm going to assume you're only using these functions in the place they're defined, so the later code would be best. It's more readable and doesn't include unnecessary identifiers.

Your question is really about anonymous functions, not closures. To answer this question, you should ask yourself, "do I plan on using these functions elsewhere"? Since anonymous functions, by definition, are not bound to an identifier, they will be inaccessible everywhere except where they are defined.

This is the version that I would recommend:

\$(function () {

var game = function () {
var gamevar1, gamevar2, ...;
action1: function (arg) {
doAction1();
}

action2: function (arg) {
doAction2();
}
}

//when a msg is received [action,param]
game.msg[0](msg[1]);
}