Jump to content

variable best practice


charlie_says
 Share

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

Just to tidy up things, you could use ES6 classes in javascript with a constructor which defines all your stuff that belongs to it. Just for syntactic sugar:
 

class Game {
  constructor() {
    this.state = 'foo';
    this.players = [];
    ...
  }

  //other methods
  update() {
    ...
  }
}

seems just a bit cleaner.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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