全局变量在Node.js中的奇怪行为

huangapple go评论126阅读模式
英文:

global variable in Node.js: weird behaviour

问题

我有下面几个JavaScript文件

homeFunction.js:
```javascript
const { testFunc2 } = require("./TestFunction");

function home(val) {
    global.context = {};
    global.context.val = val;
}

home(3);
testFunc2();

下面是TestFunction.js

exports.testFunc2 = () => {
    console.log(context.val);
}

这段代码输出3,尽管在testFunc2之前我没有使用global关键字来声明context。这是如何运作的呢?我猜测Node.js会在局部作用域中查找名为context的变量,如果在局部找不到,它会继续查找全局作用域。这个猜测正确吗?

谢谢!


<details>
<summary>英文:</summary>

I have below couple of files of javascript:

const { testFunc2 } = require("./TestFunction");

function home(val){
global.context={};

global.context.val = val;

}

home(3);
testFunc2();
//homeFunction.js

Below is `TestFunction.js`:

exports.testFunc2=()=>{
console.log(context.val);
}

This code prints 3 as the output, even though I have not put ``global`` before ``context`` in testFunc2. How does this actually works? My guess is that node looks for a variable named context in local scope, if it is not able to find it local, it moves onto global scope. Is that correct?

Thanks!

</details>


# 答案1
**得分**: 1

是的,明确的 `global` 对象是 Node.js 的一个独特特性。这是一个在 Node.js 程序中所有模块之间**共享**的对象,即使你没有积极采取任何操作来引起共享(正如你所说)。

如果没有名为 `context` 的局部变量,你对 `context` 的引用将会落到全局的 `context` 上,你可以使用 `global.context=` 来写入它。

在某种程度上,这类似于在浏览器中写入 `window.xyz`,然后导入一个尝试读取 `xyz` 的模块时会发生的情况。

<details>
<summary>英文:</summary>

### Yes, the explicit `global` object is a feature peculiar to Node JS

It is an object that is _shared_ between all the modules in a Node JS program, even when you don&#39;t feel like you are actively doing anything to cause the sharing (as you say).

If there is no local variable called `context`, your reference to `context` falls through to the global `context`, which you wrote into using `global.context=`.

In a way, it is similar to what would happen in a browser if you wrote to `window.xyz` and then imported a module that tried to read `xyz`. 

</details>



huangapple
  • 本文由 发表于 2023年4月7日 01:12:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75952108.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定