0

In the game code below (written using the Phaser framework) I am trying to pass the variable this.inputScore to the global function assignValue. The assignValue function is being read by an external Index.html file on 'game over' and I need this.inputScore to be passed to the Index.html file via the assignValue function. At the moment this.inputScore is undefined in the assignValue function. I would greatly appreciate any help - new to programming. Thank you.

//GLOBAL FUNCTION
  function assignValue() {
    document.getElementById("inputScore").value = this.inputScore; 
};

//GAME CODE
var CrystalRunner = CrystalRunner || {};

CrystalRunner.GameState = {

init: function() {
  //...code here
}, 

create: function() {
 //...code here
},  

update: function() {  
//..code here
       if(this.player.top >= this.game.world.height) {
         this.gameOver();
      }
},  

gameOver: function(){
    //..code here
    this.updateHighscore();
    //..code here
  },

  updateHighscore: function(){
    this.highScore = +localStorage.getItem('highScore');
    if(this.highScore < this.myScore){
            this.highScore = this.myScore;
            this.inputScore = this.highScore; //I need this.inputScore to be passed into the assignValue function
            this.submitScoreButton = this.game.add.sprite(this.game.world.centerX-135, this.game.world.centerY+100, 'submitScoreButton');
            this.submitScoreButton.events.onInputUp.add(function() {
                    window.location.href = "index1.php"; //Index1.php will have a form input value into which this.inputScore will be passed
              }, this);
      }
      localStorage.setItem('highScore', this.highScore);
  },
};
Asif vora
  • 1,117
  • 2
  • 8
  • 19
Steph
  • 87
  • 9
  • 1
    did you try passing as argument? assignValue(this.inputScore) – Amit Chauhan Dec 13 '18 at 05:11
  • 1
    Searching for more information on [variable scope](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) and [understanding the `this` keyword](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) will help here. – stealththeninja Dec 13 '18 at 05:13
  • If you do this: `document.getElementById("inputScore").value = CrystalRunner.GameState.inputScore;` do this work? – Shidersz Dec 13 '18 at 05:14

1 Answers1

3

You can pass value as argument.

//Global Function

function assignValue(inputScore) {
       document.getElementById("inputScore").value = inputScore; 
}

//From class

assignValue(this.inputScore);
Amit Chauhan
  • 3,990
  • 1
  • 15
  • 30