Unless you plan on running two separate games in the same page then a singleton naturally makes sense.
With that being said, it does introduce the issue of constantly referencing global variables. For a minor course on why this is an issue you might check out this article but I would really suggest reading Nicholas C. Zakas's High Performance Javascript.
The basic rundown goes a little something like this: say you've got some arbitrary function
function RunGame() {
var player = new Player();
alert(player.position.x);
for(var i = 0; i < 5; i++)
document.write(Engine.ToString() + "<br />");
}
Obviously the function is nonsense but pay attention to the scoping here. Whenever JS is looking for a variable, it starts with the inner-most scope first before heading outward. So getting the player is no big deal, the JS engine just says Hey, the player is right here, I don't need to look any farther.
But when you're referencing things out of scope, like the Engine
or even document
, it still has to see if those are local variables.
If you look at that horrible for loop that you should never consider doing ;) it references document
five different times and each of those times it has to check the local scope, any outer scope (say if this function was a part of some larger object), so on and so forth until finally getting to the global scope. All of a sudden, referencing the same object takes a lot more operations. This effect can be lessened by making references in the local scope (which I suggest you always do if a variable is used more than once)
function RunGame() {
var player = new Player(),
doc = document;
alert(player.position.x);
for(var i = 0; i < 5; i++)
doc.write(Engine.ToString() + "<br />");
}
But this still means you have to make that extra leap to global scope every time you generate your local variables. So it really depends on how intense you believe your game will be and how lazy you feel like being ;)