简体   繁体   中英

Passing a reference of a global variable to a function

Is it possible to send a link to a global variable to a function in JavaScript? This answer says no, but I cannot believe, there is no workaround.

What I mean is something like the following. It is not working, but it shall explain what I mean:

var data_1;
var data_2;

fillValue(data_1,"First");
fillValue(data_2,"Second");

function fillValue(link2GlobalVar, value){
    link2GlobalVar = value;
}   

console.log(data_1);
console.log(data_2);

It would be great if it was possible to output in the console

First
Second

Do you know a trick to send global variables to functions and change them within them like this?

See Fiddle

JavaScript doesn't have references in the same way other languages do. When you do fillValue(data_1,"First"); you are passing data_1 by value. So, you can't update data_1 because in the function all you have is a copy of the data.

If these variables are global , then you can do what the linked answer suggests and pass the variable name:

fillValue("data_1", "First");
fillValue("data_2", "Second");

function fillValue(link2GlobalVar, value){
    window[link2GlobalVar] = value;
}

UPDATE: In JavaScript, if you pass an object as a parameter, then it is actually passed by reference. You can try something like this:

var datas = {};

fillValue(datas, "data_1", ,"First");
fillValue(datas, "data_2", "Second");

function fillValue(obj, key, value){
    obj[key] = value;
}

Primitive values aren't passed by reference. Objects are.

If you wrap the globals in an object, you'll be able to modify its properties from a function:

 var data_1 = {}; var data_2 = {}; fillValue(data_1,"First"); fillValue(data_2,"Second"); function fillValue(link2GlobalVar, value){ link2GlobalVar.value = value; } document.write(data_1.value + "<br/>" +data_2.value); 

Other than that, this , should be more portable than window . (Works both in the browser and on nodejs ). You can't use it from inside functions (that aren't called with new) if you're in strict mode, but you can use it in global scope to get a reference to the global scope.

 "use strict"; var data_1; var data_2; var global = this; //get a reference to the global object fillValue("data_1","First"); fillValue("data_2","Second"); function fillValue(globalVariableName, value){ //`this` instead of `global` would work here only if you're not in strict mode global[globalVariableName] = value; } document.write(data_1 + "<br/>" +data_2); 

this question seems a little crazy but you could pass the name of the global as string and then set with an eval:

function blah(nameAsString, val){ eval("window." + name + " = " + val);}

even crazier! :)

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.

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