简体   繁体   English

ES6 模块范围

[英]ES6 module scope

I have the code:我有代码:

// 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?

Can I use "a" variable in a global scope after module importing or is it available only in a module scope?模块导入后,我可以在全局范围内使用“a”变量还是仅在模块范围内可用? Will ES6 modules have a similar working principle like this trick: 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?模块导入后,我可以在全局范围内使用“a”变量还是仅在模块范围内可用?

It's only available inside the module it was declared in.它仅在声明它的模块内可用。

Will ES6 modules have a similar working principle like this trick: [...] ES6 模块是否有类似这个技巧的类似工作原理:[...]

Basically yes.基本上是的。


ES6 has these kinds of scopes, order from "top" to "bottom": ES6 有这些范围,从“顶部”到“底部”排序:

  • Global scope全球范围
  • Module scope模块范围
  • Function scope功能范围
  • Block scope块作用域

You can do globalThis.a = "a" and access it after that module has loaded.您可以执行globalThis.a = "a"并在该模块加载后访问它。 See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis请参阅: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis

lets say you are exporting something to another module.假设您正在将某些内容导出到另一个模块。 example you are exporting var b = 'b' , but you are not exporting the var a = 'a' .例如,您正在导出var b = 'b' ,但您没有导出var a = 'a' this means you are only able to use var a = 'a' in lib.js , It is local to the module it was declared in and only can be used in that module.这意味着您只能在lib.js使用var a = 'a' ,它是声明它的模块的本地模块,并且只能在该模块中使用。 var a is scoped to the lib.js module. var a的范围是lib.js模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM