Jump to content
Sign in to follow this  
astralaaron

How may I structure my code into separate files?

Recommended Posts

I have a work project that has become quite large, and I am now required to separate each object of the code into it's own file. The following code example is how it is structured currently, all in one giant file.
function Main() {
  var main = this;

  this.init = function() {
    // code
     main.keyboard.init();
     main.game_loop.init();
     main.physics.init();
  }

  this.keyboard = {
    init: function() { },
    keys: { UP:38, DOWN:40, LEFT:37, RIGHT:39 }
    input: function(e) {
      // functions reference 'main' variable
    }
  }

  this.game_loop = {
    init: function() { },
    on_frame: function() {
        // functions reference 'main' variable

    }
  }

  this.physics = {
    init: function() {
        // functions reference 'main' variable
    }
  }

}

$(document).ready(function(){
  var m = new Main();
  m.init();
});

I have tried separating the objects into their own file's and changing them, for example from:

this.keyboard = { }

to

Main.prototype.keyboard = { }

However I then no longer have access to the 'main' variable.   Someone has suggested "arrow functions" to me, but I was just confused on how to apply that to my code. I really appreciate anyone who looks at this.

Share this post


Link to post
Share on other sites

You need to specify that the other objects execute in the same scope as Main.  Arrow functions can do that, when you define the function you can also tell it what scope to run in.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×