简体   繁体   中英

JavaScript function - pass variable and create global variable from it

I created this function

function calc (a, b, variableName){
  variableName = a * b;
}

The point is multiple a and b and create global variable

calc(2, 5, first);
calc(3, 5, second);

First function call should be first = 10; second call should be second = 15;

But it not works, how can I get global variable and define its name in function call?

Have the function return the value and then assign the result of the function call to a variable.

function calc (a, b){ 
  return  a * b; 
}


first = calc(2, 5);
second = calc(3, 5);

JavaScript is pass by value . but global variables declared using var (not let or const ) are represented on the global object ( window in browsers), and the reverse (ie defining properties on the global object are available in the global scope) is possible as well.

So, just pass the name of the variable you want to alter as a string—instead of the value—then alter the corresponding property on the global object.

Keep in mind that polluting the global scope is generally not a good idea unless absolutely necessary for the application.

 const alter = (prop, val) => Object.assign(window, { [prop]: val }); // Define a global variable var test = 1; // Alter the global variable alter('test', 2); console.log(test); // Create a new global variable alter('hello', 'world'); console.log(hello); 

This concept applied to your specific example:

 function calc(a, b, variableName) { window[variableName] = a * b; } calc(2, 5, 'first'); calc(3, 5, 'second'); console.log(first, second); 

Really not recommended... but if you are doing this inside a Web browser, you can attach them to the window object and then they will be available directly by name. Note the variable names must be passed as strings:

 function calc (a, b, variableName){ window[variableName] = a * b; } calc(2, 5, 'first'); calc(3, 5, 'second'); console.log(first); console.log(second); 

There are ways to do this. The first is exactly what you are describing but isn't a very good idea.

▶ node
> global.a = 5
5
> a
5

The global object in node makes all of it's children in the global scope.

Same thing as Tiny Giant described but for backend.

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