如何在局部范围内更改全局变量的值?



我需要在函数范围内更改全局变量的值。

const func = () => {
let a = 'a';
const alter = () => {
a = 'c';
}
const ver = () => {
console.log(a)
}
alter()
ver()
}
func();

听起来你可能正在为作用域在 JavaScript 中的工作方式而苦苦挣扎。

首先,您的示例中没有声明全局变量。调用alter时,它会查找其范围内不存在a。所以它看向外镜,这是func.funca声明,所以这是作用域链结束的地方,被修改的afunc内部

的那个。如果你想a是"全局的",你必须在任何函数的范围之外解除声明。这将导致您的示例修改全局范围内的a

但是,如果您保持示例原样并在全局范围内声明另一个a(即您有两个a声明(,那么您的示例将修改func而不是全局a中的a值。

如果要在作用域链中间有另一个同名变量时修改全局变量,可以执行以下操作:

let a = 'b'; // this is our global `a` declaration
const func = () => {
let a = 'a'; // here we declare a new `a` inside the scope of `func`
const alter = () => {
window.a = 'c'; // modifies the global `a`
}
const ver = () => {
console.log(window.a); // this will log `c`
/* 
* This log below will output `a` as it is referencing the first `a`
* declared along the scope chain, which is in `func` (the outer scope)
* and it hasn't been modified.
*/
console.log(a);
}
alter();
ver();
}
func();

最新更新