ES6模块范围 [英] ES6 module scope

查看:95
本文介绍了ES6模块范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有代码:

// 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模块是否具有类似此技巧的类似工作原理:

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:

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

推荐答案

模块导入后,我可以在全局范围内使用"a"变量吗?还是仅在模块范围内可用?

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

仅在声明它的模块内部可用.

It's only available inside the module it was declared in.

ES6模块是否具有类似此技巧的工作原理:[...]

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

基本上是.

ES6具有以下范围,从顶部"到底部"的顺序:

ES6 has these kinds of scopes, order from "top" to "bottom":

  • 全球范围
  • 模块作用域
  • 功能范围
  • 块范围

这篇关于ES6模块范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆