在另一个模块中调用使用全局变量的函数

Calling function that uses global variable in another Module

如果我在其模块中定义了一个依赖(使用)全局变量的函数,如果我导出它并尝试在该模块外调用它会发生什么情况?

我已经尝试过了,发现它可以正常工作,尽管我无权访问该变量(它未在我的范围内定义)。所以我想确定我是否理解这一点,这是否就像闭包函数一样,函数从词法范围获取它的变量?

PS: 我的问题与ES6模块特性有关。

#添加真正简单的例子

这是我的html:只是一个脚本

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script type="module" src="app.js"></script>
  </body>
</html>

这是我的模块文件:

let globalVariable = "I cannot be accessed outised this module";
export function testFunction() {
  console.log(globalVariable);
}

这是我的 app.js 文件:

import { testFunction } from "./module.js";

testFunction();

尽管在 app.js 中无法访问 globalVariable,但该消息已打印在控制台中。

let globalVariable = "I cannot be accessed outised this module";

那不是全局的。它只是模块范围内的一个变量。

export function testFunction() {
  console.log(globalVariable);
}

这个函数访问名为 globalVariable 的变量,无论它(函数)传递到哪里,就像任何其他闭包一样。

进一步阅读:How do JavaScript closures work?