简体   繁体   中英

How to pass local variable to global function

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);
  },
};

You can pass value as argument.

//Global Function

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

//From class

assignValue(this.inputScore);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM