I want to know if it is possible to pass a global variable in JavaScript by name to a function?
In my use case, I have two global variables abc
and xyz
. When function1()
is called, I make an AJAX call and want to use the response to some work and assign value to variable abc
. This same functionality exists for function2()
and variable xyz
. So I want to extract this assignValueToVariable()
function and make it a util method.
But the problem is, if I pass the global variable name like I am doing in function2()
, then xyz
in global scope is always undefined. How can I make this work so that I can use the same assignValueToVariable()
method in function1()
and function2()
?
<button type="button" onclick="otherfunction();">Click Me</button>
var abc,
xyz;
function1();
function2();
function function1() {
//ajax call - get data and pass it to function
data = "123";
// this works. Since I'm directly refering global variable in the function
assignValueToVariableABC(data);
}
function function2() {
//ajax call - get data;
data = "456";
// this doesn't set the value to global variable
assignValueToVariable(xyz, data);
}
function otherfunction() {
//xyz is undefined here
console.log(abc + "--" + xyz);
}
function assignValueToVariable(varName, data) {
//assign value from data to variable
varName = data;
}
function assignValueToVariableABC() {
//assign value from data to variable
abc = data;
}
When you call assignValueToVariable(xyz, data);
you are not passing in the variable name "xyz", you are passing the value that is stored in xyz
, when you have simple types like strings and numbers. That's why assigning a value to varName
doesn't change it outside that function, it's essentially a copy.
You could store the global data in an object, because then you can pass in a string to be used as a key:
var globalobject = {
"xyz": "foo",
"abc": "bar"
};
function function2() {
assignValueToGlobal("xyz", 123);
}
function assignValueToGlobal(varName, data)
{
globalobject[varName] = data;
}
function2();
console.log(globalobject);
To clarify further, in JavaScript primitive types (strings, numbers) are passed by value (essentially the value is copied and then passed). Objects are passed by copy of the reference pointing to the original, which is a bit quirky and different from many languages.
Maybe you can use something like this:
function assignValueToVariable(globalObj, someKey) {
return function (retVal) {
globalObj[someKey] = retVal;
};
}
var setAbc = assignValueToVariable(window, 'abc'),
setXyz = assignValueToVariable(window, 'xyz');
makeAjaxCall(setAbc);
// etc
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.