关于Node.js中的全局变量 [英] About global variables in Node.js

查看:124
本文介绍了关于Node.js中的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Node.js似乎使用不同的规则将变量附加到global对象,无论是在REPL中还是在脚本中完成.

Node.js seems to use different rules to attach variables to the global object whether this is done in the REPL or in a script.

$ node
> var a = 1;
undefined
> a
1
> global.a
1
> a === global.a
true

如上所示,在REPL中工作时,用var声明变量会在global对象上创建一个具有该变量名称的新属性.

As shown above when working in the REPL, declaring a variable with var creates a new property with the name of that variable on the global object.

但是,在脚本中似乎并非如此:

However, this doesn't seem to be the case in a script:

// test.js

var a = 1;
console.log(a);
console.log(global.a);
console.log(a === global.a);

让我们运行脚本:

$ node test.js
1
undefined
false

为什么会这样?

推荐答案

运行脚本时,它将脚本包装在模块中.脚本中的顶级变量位于模块函数内部,而不是全局变量.这是node.js加载和运行脚本的方式,无论是在初始命令行上指定还是使用require()加载.

When a script is run, it is wrapped in a module. The top level variables in a script are inside a module function and are not global. This is how node.js loads and runs scripts whether specified on the initial command line or loaded with require().

在REPL中运行的代码未包装在模块函数中.

Code run in the REPL is not wrapped in a module function.

如果希望变量是全局变量,则可以将它们专门分配给global对象,这将在脚本或REPL中起作用.

If you want variables to be global, you assign them specifically to the global object and this will work in either a script or REPL.

 global.a = 1;

在node.js中通常不会使用全局变量.而是通过模块导出,模块构造函数或其他模块方法将引用传递给特定模块,从而根据需要在特定模块之间共享变量.

Global variables are generally frowned upon in node.js. Instead variables are shared between specific modules as needed by passing references to them via module exports, module constructors or other module methods.

在node.js中加载模块时,该模块的代码将插入到函数包装中,如下所示:

When you load a module in node.js, the code for the module is inserted into a function wrapper like this:

(function (exports, require, module, __filename, __dirname) {
     // Your module code injected here
});

因此,如果在模块文件的顶层声明变量a,则代码将最终由node.js执行,如下所示:

So, if you declare a variable a at the top level of the module file, the code will end up being executed by node.js like this:

(function (exports, require, module, __filename, __dirname) {
      var a = 1;
});

由此,您可以看到a变量实际上是模块函数包装器中的局部变量,而不是全局范围中的局部变量,因此,如果要在全局范围中使用它,则必须将其分配给全局对象

From that, you can see that the a variable is actually a local variable in the module function wrapper, not in the global scope so if you want it in the global scope, then you must assign it to the global object.

这篇关于关于Node.js中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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