charlie_says Posted October 24, 2016 Share Posted October 24, 2016 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 More sharing options...
trueicecold Posted October 24, 2016 Share Posted October 24, 2016 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 More sharing options...
charlie_says Posted October 24, 2016 Author Share Posted October 24, 2016 thanks @trueicecold, looks like I was going in the right direction (this time!) Link to comment Share on other sites More sharing options...
s4m_ur4i Posted October 24, 2016 Share Posted October 24, 2016 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 More sharing options...
Recommended Posts