ES6 模块作用域

ES6 module scope

我有代码:

// lib.js
var a = "a";
export var b = "b";

// main.js
console.log(a); // "a" variable is not available in a global scope
import {b} from "lib";
console.log(a); // is "a" variable available in a global scope or only in a module scope?

我可以在模块导入后在全局范围内使用 "a" 变量吗?还是只能在模块范围内使用? ES6模块会不会有类似这样的工作原理:

// module    
exports.module1 = (function(){ var a = "a"; })(); // "a" variable is not available in a global scope

Can I use "a" variable in a global scope after module importing or is it available only in a module scope?

它仅在声明它的模块内可用。

Will ES6 modules have a similar working principle like this trick: [...]

基本上是


ES6 有这些范围,顺序从 "top" 到 "bottom":

  • 全球范围
  • 模块范围
  • 函数范围
  • 块范围

假设您正在将某些内容导出到另一个模块。例如,您正在导出 var b = 'b',但没有导出 var a = 'a'。这意味着您只能在 lib.js 中使用 var a = 'a',它在声明它的模块中是本地的,并且只能在该模块中使用。 var a 的范围是 lib.js 模块。

您可以执行 globalThis.a = "a" 并在该模块加载后访问它。参见:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis