Jump to content

variable best practice


Recommended Posts

I realised today, that I'd been working on my game much in the same way as the Phaser examples, and I had a question about best practice for variables.

As per the examples, I tend to declare varaibles at the top, which is fine apart from 2 things, firstly this makes them globally available, secondly it makes them a little difficult to access dynamically (I end up using window["dyn_var_"+n] etc.)

But, I have also add vars to the game function like this:

Game.Play = function (game) { 

  this.player1 = [];
  this.numBalls = 6;


which means they are accessible throughout the Play state.

But, I wondered if there was another way, a better way, or what was generally considered best (or maybe better) practice?


Link to comment
Share on other sites

variables that belong to a state should be used with the "this" keyword, making it relevant to that instance alone.

As for players, I would suggest using an array of players: players[0] and players[1] instead of this["players" + n]. Or better yet, save the position of the current player (if it's turn based):


this.currentPlayerIndex = 2;
this.players[this.currentPlayerIndex].start(); //or whatever...


Link to comment
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.
Note: Your post will require moderator approval before it will be visible.

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.


  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...