我在用 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!");
}
}
游戏的工作原理是每个功能(定义为游戏中的 Action 或区域)将由 JavaScript 放置的按钮和表单调用,用户可以分别单击或写入。我需要 refreshStats() 来更新 health 和 exp 变量,以便 foo() 可以正确使用它们;该函数似乎在 foo() 运行之后才更新变量。我确实想知道这是否是浏览器兼容性问题,这真的会让我失望,但我希望不是那样。
有什么建议吗?
最佳答案
将您的值存储到您的窗口对象中,因此它将在该窗口的任何范围内可用:
//take care to not overwrite native properties of the window
window.health = 100;
window.exp = 0;
function refreshStats() {
health -= 10;
exp += 1;
}
关于JavaScript - 函数不修改全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7291352/