nodejs 模块中的全局对象是什么? [英] What's the global object within a module in nodejs?
问题描述
我知道在 node 中,每个模块都有一个局部作用域,并且在一个模块中定义的变量不会转义到全局,除非明确导出.
I know in node, every module gets an local scope and variable defined within one module won't escape to the global unless explicitly exported.
我想知道的是,当我在一个模块文件中如下声明一个变量时,这个变量定义的全局对象是什么?
What I want to know is when I declare a variable in one module file as the following, what's the global object this variable defined on?
var obj = {};
// In browser, this is defined on window.obj
// How about in the node?
有一个声明,global
是用作局部全局作用域的对象,但是以下测试代码失败:
There is one statement that global
is the object used as the local global scope, however the following test code fails:
a = 1
console.log global.a
// undefined
那么什么是模块的全局变量?
So what is the global variable for a module?
推荐答案
node里面其实有一个全局对象;它简称为global
.您可以为它分配属性并像访问任何其他对象一样访问这些属性,并且可以跨模块执行此操作.然而,直接访问它(global.foo=bar
在一个模块中,baz=global.foo
在另一个模块中)是唯一访问方式它.非限定变量名永远自动解析为其属性,例如,浏览器环境中的非限定变量名解析为window.somethingOrOther
.在 node 中,每个模块在概念上都包含在一个立即函数调用中,因此非限定名称代表局部变量并具有模块级作用域.
There is in fact a global object in node; it's simply called global
. You can assign properties to it and access those properties just like any other object, and you can do it across modules. However, directly accessing it (global.foo=bar
in one module, baz=global.foo
in another) is the only way to access it. Unqualified variable names never automatically resolve to its properties the way that, say, an unqualified variable name in a browser environment would resolve to window.somethingOrOther
. In node, every module is conceptually wrapped inside an immediate function call, so unqualified names represent local variables and have module-level scope.
这篇关于nodejs 模块中的全局对象是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!