microcipcip Posted December 17, 2015 Share Posted December 17, 2015 Hi,I am new to PhaserJS and I have been learning the basics with the Interphase book. I would like to know why is everything defined inside the prototype? Is this for avoiding performance issues? Common practice? Or because I am going in this way you can reuse the State several times in the game?Also, what is the purpose of defining objects properties inside the function and then use them in the prototype? For example, see this.sprite and this.bg in the example below; is this a way of sharing the parameters across states? var MyGame = {};MyGame.StateA = function (game) { this.sprite = null; this.bg = null;};MyGame.StateA.prototype = { preload: function () {}, create: function () {}}; Link to comment Share on other sites More sharing options...
strawlion Posted December 17, 2015 Share Posted December 17, 2015 I can't speak for Phaser specifically, but the reason to define functions on the prototype in JavaScript is indeed performance related. Any object that extends from that prototype will share the same instance of the function, whereas if it were declared directly on the object a new instance would be created for each instance of that object type. This means you're saving both memory and whatever processing time it takes to create that function for each object.Some could argue it's more semantic to group these on the prototype. In most cases this performance discrepancy isn't so important, but certainly could be in game development Link to comment Share on other sites More sharing options...
microcipcip Posted December 18, 2015 Author Share Posted December 18, 2015 Thanks for the reply. What about the initialization of the parameters inside the function? Is this a common way to share/reference them inside the prototype and across game states? Link to comment Share on other sites More sharing options...
shohan4556 Posted December 18, 2015 Share Posted December 18, 2015 here is some good explanation http://stackoverflow.com/questions/8433459/js-why-use-prototype Link to comment Share on other sites More sharing options...
Recommended Posts