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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...