Jump to content

  • Log In with Google      Sign In   
  • Create Account


#ActualHappyCoder

Posted 21 March 2013 - 11:30 AM

A trick you can do in javascript is wrap everything in a single function and that takes them all out of the global scope.

So lets say you have all of the following global variables declared as such.
var a = 0;
var b = 1;

function doStuff()
{
    ++a;
}
...
You can wrap that code like this
function GameOne()
{
   var a = 0;
   var b = 1;

   function doStuff()
   {
       ++a;
   }
   ...
}
Now all of those variables are local variables to a function so there will be no conflicts. Then to run the code you simply call the function.
GameOne();
If you want to jump between games you will have to ensure that the first game you are coming from cleans up its event listeners and that its game loop exits.

This hack would seem to be a quick solution to your current problem, although I wouldn't recommend this solution for any new projects you start. Doing it this way requires you to reimplement your game loop and other code in every source file. Ideally you want to get rid of any duplicate code.

And if you need to get any local variables you can add a getter.
function GameOne()
{
   var a = 0;
   ...

   GameOne.getA = function()
   {
      return a;
   }
}
Then to use the getter you simply call GameOne.getA().

#1HappyCoder

Posted 21 March 2013 - 11:29 AM

A trick you can do in javascript is wrap everything in a single function and that takes them all out of the global scope.

So lets say you have all of the following global variables declared as such.
var a = 0;
var b = 1;

function doStuff()
{
    ++a;
}
...
You can wrap that code like this
function GameOne()
{
   var a = 0;
   var b = 1;

   function doStuff()
   {
       ++a;
   }
   ...
}
Now all of those variables are local variables to a function so there will be no conflicts. Then to run the code you simply call the function.
GameOne();
If you want to jump between games you will have to ensure that the first game you are coming from cleans up its event listeners and that its game loop exits.

This hack would seem to be a quick solution to your current problem, although I wouldn't recommend this solution for any new projects you start. Doing it this way requires you to reimplement your game loop and other code in every source file. Ideally you want to get rid of any duplicate code.

And if you need to get any local variables you can add a getter.
function GameOne()
{
   var a = 0;
   ...

   GameOne.getA = function()
   {
      return a;
   }
}

PARTNERS