如何将局部变量传递给全局函数

时间:2018-12-13 05:09:18

标签: javascript

在下面的游戏代码中(使用Phaser框架编写),我试图将变量this.inputScore传递给全局函数assignValueassignValue函数正在'game over'上由外部Index.html文件读取,我需要通过this.inputScore函数将assignValue传递到Index.html文件。目前this.inputScore在assignValue函数中未定义。我将不胜感激任何帮助-编程新手。谢谢。

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

1 个答案:

答案 0 :(得分:3)

您可以将值作为参数传递。

//Global Function

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

//From class

assignValue(this.inputScore);