简体   繁体   English

JavaScript函数-传递变量并从中创建全局变量

[英]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 点是多个a和b并创建全局变量

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

First function call should be first = 10; 第一个函数调用应为first = 10; second call should be second = 15; 第二次通话应为秒= 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 . JavaScript是按值传递的 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. 但是使用var声明的全局变量(不是letconst在全局对象 (浏览器中的window )上表示 ,并且相反(也就是在全局范围内定义全局对象的属性)也是可能的。

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. 确实不建议使用...,但是如果在Web浏览器中执行此操作,则可以将它们附加到window对象,然后按名称直接可以使用它们。 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. 节点中的global对象使其成为全局范围内的所有子代。

Same thing as Tiny Giant described but for backend. 与Tiny Giant所描述的相同,只是用于后端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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