JavaScript - 函数不修改全局变量

发布于 2024-12-03 04:08:47 字数 712 浏览 1 评论 0原文

我在用 JavaScript 编写代码的文本冒险游戏中修改变量时遇到问题。我想使用函数内的函数更改全局变量的值(不,不是闭包)。

/*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!");
      }
    }

游戏的工作原理是,每个功能(定义为游戏中的动作或区域)将由 JavaScript 放置的按钮和表单调用,用户可以分别单击或写入。我需要refreshStats()来更新health和exp变量,以便foo()可以正确使用它们;该函数似乎直到 foo() 运行后才更新变量。我确实想知道这是否是浏览器兼容性问题,这确实会让我生气,但我希望不是这样。

有什么建议吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

囚你心 2024-12-10 04:08:47

将您的值存储到窗口对象中,因此它将在该窗口的任何范围内可用:

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

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

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;
}
何以畏孤独 2024-12-10 04:08:47

看起来它对我有用。也许这是一个范围问题 - 您可以发布实际的相关代码而不是示例代码吗?

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文