Jump to content

this.game, this.rnd, .etc undefined when using prototypes?


bloosnail
 Share

Recommended Posts

Hi all, 

I am in the process of refactoring my code to use states for menus and loading screens. I'm trying to use the Basic template (https://github.com/photonstorm/phaser/tree/master/resources/Project Templates/Basic) and am having issues with this.game and this.rnd being undefined when passing it into functions in the prototype. The parts with issue look something like:

 

BasicGame.Game = function (game){
  this.game;
  this.rnd;

  ...

};

BasicGame.Game.prototype = {
  create : function(){

    //code that creates enemy group
    BasicGame.Game.prototype.launchEnemy();

    ...
  }
},

  launchEnemy : function (){
    var choice = this.rnd.integerInRange(1,4);
    //code that launches enemy

    BasicGame.Game.prototype.launchEnemy();
  },

...
//rest of code
...

};

 

And this.rnd and this.game are both undefined. I tried doing something like:

BasicGame.Game = function (game){
  this.game;
  this.rnd;

  ...

};

BasicGame.Game.prototype = {
  create : function(){

    //code that creates enemy group
    BasicGame.Game.prototype.launchEnemy(this.game, this.rnd);

    ...
  }
},

  launchEnemy : function (myGame, myRnd){
    var choice = myRnd.integerInRange(1,4);
    //code that launches enemy

    BasicGame.Game.prototype.launchEnemy(myGame, myRnd);
  },

...
//rest of code
...

};

Without passing the myGame and myRnd to the recursive call one enemy is spawned before the variables are undefined, and then when I do pass them into the recursive call the console says "too much recursion" and nothing happens. I think there should be a stop case for the recursion, but am wondering if there is a more practical way of dealing with this, like making this.rnd and this.game visible to all the functions within the prototype? I tried declaring a variable outside the prototype with the rest of my variables eg. var myGame = this.game, but it was undefined when trying to use it.

 

Any help is appreciated, thanks!

Link to comment
Share on other sites

Hi bloosnail, within those methods you should reference the current state as this:

BasicGame.Game.prototype = {

    create: function (){
        this.launchEnemy();
    },

    launchEnemy: function (){
        var choice = this.rnd.integerInRange(1,4);
        // …
    },

};

The "too much recursion" problem is happening because BasicGame.Game.prototype.launchEnemy is calling itself.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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