在函数内设置全局变量

setting global variables inside a function

本文关键字:全局变量 设置 函数      更新时间:2023-09-26

我正在尝试创建一个函数,该函数将动态设置作为参数传递的任何全局变量的值。它不起作用,我试图找出原因。有人可以解释为什么这不起作用:

var things = 5;
function setup(variable) {
    variable = 7;
}
setup(things);
console.log(things); //should return 7. returns 5 instead. the function had no effect on the global variable

这也不起作用:

var things = 5;
function setup(variable) {
    window.variable = 7;
}
setup(things);
console.log(things); //should return 7, but returns 5. still not accessing the global variable.

但这确实:

var things = 5;
function setup(variable) {
    window[variable] = 7;
}
setup("things");
console.log(things); //returns 7

我怀疑正在发生的事情是参数variable被设置为函数内部的局部变量,因此任何更改都只发生在本地版本上。但这似乎很奇怪,因为传递的参数是一个全局变量。有人可以向我解释正在发生的事情以及如何更好地编写此代码吗?这是否需要一种方法(然后可以使用this来访问原始对象)?

谢谢!!

Javascript 是按值传递的。(对象、数组和其他非基元按引用值传递。这意味着变量(或引用)的值将传递给函数,但函数参数不会成为实际参数的别名。因此,如果不引用变量,就无法更改函数外部的变量(如上一个示例中所做的那样)。

有关详细信息,请参阅另一个线程中的此答案。

函数内部是"可变环境"。声明函数设置并设置参数变量时,它会在安装程序的变量环境中为 variable(参数)创建一个局部变量。

所以这就是为什么这个任务

function setup(variable) {
 variable = 7;
}

永远不会更改发送到变量的值。

JavaScript 中的变量是值。当变量被传递时,唯一传递的是变量的值。但是,变量的值被分配给参数(在本例中同样命名不佳)variable 。当参数的值赋值为 7 时,这只会更改局部变量,而不会更改传递变量的值。

//the value of things is 5
var things = 5;
//the passed value 5 is assigned to variable
function setup(variable) {
  //the value of variable is changed to 7 (and nothing is done with 5)
  variable = 7;
}
//the value of things is sent to setup
setup(things);

希望这会更有启发性。考虑setup实际上正在修改变量值的情况。一个很好的例子是当值具有状态时,例如数组或对象。

//the value of things this time is an object
var things = {};
//the passed value of object is assigned to variable
function setup(variable){
 //the value of variable (the object) has a property added named msg with a value of "hello world"
 variable.msg = "hello world";
}
//the value of things (an object) is sent to setup
setup(things);
alert(things.msg);//hello world

当变量作为参数传递给函数时,会创建其值的副本并将其分配给函数中参数的名称。

例如:

function foo(a) {
    a = 7; // sets the temporary variable(argument) a to 7
}
var bar = 24; 
foo(bar); // copies bar's value and passes in the copy to foo

对于要修改变量本身的函数,您必须以另一种方式访问它。在其他语言中,有一些东西称为指针,指向内存中的某个位置。这允许你直接修改变量,因为它们的位置 - 你可以用JavaScript模拟:

var spam = 3;
var memory = ["bar", 29, "x", foo, false];
function foo(a) {
    memory[a] = 7;
}
foo(3);

上面的例子设置了一个名为 memory 的数组,并用随机乱码填充它。然后,创建一个名为 foo 的函数,该函数允许修改此内存数组中的元素。