简体   繁体   中英

JavaScript - Function Not Modifying Global Variable

I'm having trouble modifying a variable within a text adventure game I'm writing code for in JavaScript. I want to change the value of a global variable using a function within a function (no, not closure).

/*This is just example code.*/
    var health = 100;
    var exp = 0;

    function refreshStats() {
      health -= 10;
      exp += 1;
    }

    function foo(flag) {
      if (flag == DONOTHING) {
        refreshStats();
      }

      if (health <= 0) {
        say("You died, bwahaha.");
      }

      if ((exp/10) == Math.floor(exp/10)) {
        health += 10;
        say("You leveled up!");
      }
    }

How the game works is that each function (defined as actions or areas within the game) will be called by buttons and forms placed by JavaScript that the user can click or write in, respectively. I need refreshStats() to update the health and exp variables so foo() can use them correctly; the function doesn't seem to be updating the variables until after foo() runs. I do wonder if it's a browser compatibility issue, which really would tick me off, but I'm hoping it isn't that.

Any suggestions?

Store your values into your window object, so it will be available in any scope of that window:

//take care to not overwrite native properties of the window
window.health = 100;
window.exp = 0;

function refreshStats() {
  health -= 10;
  exp += 1;
}

It looks like it's working for me . Perhaps it's a scoping issue - instead of example code, could you post your actual relevant code?

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