javascript - 在函数内设置全局变量 [英] javascript - setting global variables inside a function

查看:144
本文介绍了javascript - 在函数内设置全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create a function which will dynamically set the value of whatever global variable is passed as a parameter. It's not working, and I'm trying to figure out why. Can someone please explain why this doesn't work:

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

没有影响,这也不起作用:

and this also doesn't work:

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

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

I suspect that what is happening is that the parameter variable is being set as a local variable inside of the function, so any changes are only happening to the local version. But this seems strange because the parameter that's been passed is a global variable. Can someone explain to me what is happening and how to better write this code? Does this require a method (which can then use this to access the original object)?

谢谢!

推荐答案

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

Javascript is pass-by-value. (Objects, arrays, and other non-primitives are passed by value-of-reference.) That means that the value of the variable (or reference) is passed to the function, but the function parameter does not become an alias for the actual argument. Thus, you cannot change a variable outside a function without referencing it (as you do in your last example).

请参阅这个答案在另一个主题中以获取更多信息。

See this answer in another thread for more information.

这篇关于javascript - 在函数内设置全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆