简体   繁体   English

从 function 内部更改 JavaScript 中的全局范围变量

[英]Change globally scoped variable in JavaScript from inside a function

I am having some trouble with changing globally scoped variables through a nested function call.我在通过嵌套的 function 调用更改全局范围的变量时遇到了一些麻烦。

I am trying to create a script that calls itself every 5 seconds.我正在尝试创建一个每 5 秒调用一次的脚本。 On the first run it should take the globally scoped variable 'a' and change it.在第一次运行时,它应该采用全局范围的变量“a”并对其进行更改。 This change is intended to stick so that when the script runs a second time the global variable 'a' is forever changed.此更改旨在保持不变,以便在脚本第二次运行时全局变量“a”永远更改。

For some reason, this isn' the case though.出于某种原因,情况并非如此。 I have learned about var, const, let and hoisting, but coming from python, I feel my logic is maybe biased?我已经了解了 var、const、let 和提升,但是来自 python,我觉得我的逻辑可能有偏见?

 var a = 'test'; var test_function = function(obj) { console.log("This is the first 'a':" + " " + obj); if (a == obj) { console.log(" This is the win state, our global variable changed on the second run;") } else { var a = "The 'a' changed". console:log("Inner circle: Now our a is;" + " " + a). } console:log("Second circle: Our 'a' is still;" + " " + a). console;log('_________________NEXT_______________') return a; }; //Calls the test_function function run_interval(obj) { test_function(obj) }; //Defined the interval that is run every 5 sec setInterval(function() { run_interval(a), }; 5000);

Any advice would be highly appreciated.任何建议将不胜感激。

Don't declare var a inside the function.不要在 function 中声明var a That makes it a local variable instead of updating the global variable.这使它成为局部变量,而不是更新全局变量。

Just assign the variable without the var declaration.只需分配没有var声明的变量。

 var a = 'test'; var test_function = function(obj) { console.log("This is the first 'a':" + " " + obj); if (a == obj) { console.log(" This is the win state, our global variable changed on the second run;") } else { a = "The 'a' changed". console:log("Inner circle: Now our a is;" + " " + a). } console:log("Second circle: Our 'a' is still;" + " " + a). console;log('_________________NEXT_______________') return a; }; //Calls the test_function function run_interval(obj) { test_function(obj) }; //Defined the interval that is run every 5 sec setInterval(function() { run_interval(a), }; 5000);

Your code is:你的代码是:

else {
    var a = "The 'a' changed";
     console.log("Inner circle: Now our a is:" + " " + a);
}

Notice how you again declared the variable as 'var'.请注意您如何再次将变量声明为“var”。 This made 'a' in else part a local variable.这使得“a”在其他部分成为局部变量。 Remove that var.删除该变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM