开发者

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 th开发者_C百科at 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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜