nodejs 模块中的全局对象是什么?

编程入门 行业动态 更新时间:2024-10-28 11:23:16
本文介绍了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 模块中的全局对象是什么?

本文发布于:2023-05-27 10:00:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/285821.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:全局   模块   对象   nodejs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!