Javascript ES6 export const vs export let

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32558514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:37:10  来源:igfitidea点击:

Javascript ES6 export const vs export let

javascriptecmascript-6es6-modules

提问by Cheng

Let's say I have a variable that I want to export. What's the difference between

假设我有一个要导出的变量。有什么区别

export const a = 1;

vs

对比

export let a = 1;

I understand the difference between constand let, but when you export them, what are the differences?

我明白之间的差别constlet,但是当你导出它们,有什么区别?

回答by FelisCatus

In ES6, imports are live read-only views on exported-values. As a result, when you do import a from "somemodule";, you cannot assign to ano matter how you declare ain the module.

在 ES6 中,imports 是导出值的实时只读视图。因此,当您这样做时import a from "somemodule";a无论您a在模块中如何声明,都无法分配给。

However, since imported variables are liveviews, they do change according to the "raw" exported variable in exports. Consider the following code (borrowed from the reference article below):

但是,由于导入的变量是实时视图,它们确实会根据导出中的“原始”导出变量而变化。考虑以下代码(从下面的参考文章中借用):

//------ lib.js ------
export let counter = 3;
export function incCounter() {
    counter++;
}

//------ main1.js ------
import { counter, incCounter } from './lib';

// The imported value `counter` is live
console.log(counter); // 3
incCounter();
console.log(counter); // 4

// The imported value can't be changed
counter++; // TypeError

As you can see, the difference really lies in lib.js, not main1.js.

如您所见,区别真正在于lib.js,而不是main1.js



To summarize:

总结一下:

  • You cannot assign to import-ed variables, no matter how you declare the corresponding variables in the module.
  • The traditional let-vs-constsemantics applies to the declared variable in the module.
    • If the variable is declared const, it cannot be reassigned or rebound in anywhere.
    • If the variable is declared let, it can only be reassigned in the module (but not the user). If it is changed, the import-ed variable changes accordingly.
  • import无论您如何在模块中声明相应的变量,都不能分配给-ed 变量。
  • 传统的let-vs-const语义适用于模块中声明的变量。
    • 如果声明了变量const,则不能在任何地方重新分配或重新分配。
    • 如果声明了变量let,则只能在模块中重新分配(但不能在用户中重新分配)。如果更改,import-ed 变量会相应更改。

Reference: http://exploringjs.com/es6/ch_modules.html#leanpub-auto-in-es6-imports-are-live-read-only-views-on-exported-values

参考:http: //exploringjs.com/es6/ch_modules.html#leanpub-auto-in-es6-imports-are-live-read-only-views-on-exported-values

回答by slomek

I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).

我认为一旦你导入它,行为是一样的(你的变量将在源文件之外使用)。

The only difference would be if you try to reassign it before the end of this very file.

唯一的区别是如果您尝试在此文件结束之前重新分配它。