简体   繁体   English

Javascript ES6导出const vs export let

[英]Javascript ES6 export const vs export let

Let's say I have a variable that I want to export. 假设我有一个我要导出的变量。 What's the difference between 有什么区别

export const a = 1;

vs VS

export let a = 1;

I understand the difference between const and let , but when you export them, what are the differences? 我理解constlet之间的区别,但是当你导出它们时,有什么区别?

In ES6, import s are live read-only views on exported-values. 在ES6中, import是导出值的实时只读视图。 As a result, when you do import a from "somemodule"; 因此,当您import a from "somemodule"; , you cannot assign to a no matter how you declare a in the module. ,你不能分配到a无论你如何声明a在模块中。

However, since imported variables are live views, 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. 无论如何在模块中声明相应的变量,都无法分配import变量。
  • The traditional let -vs- const semantics applies to the declared variable in the module. 传统的let -vs- const语义适用于模块中声明的变量。
    • If the variable is declared const , it cannot be reassigned or rebound in anywhere. 如果变量被声明为const ,则无法在任何地方重新分配或反弹。
    • If the variable is declared let , it can only be reassigned in the module (but not the user). 如果变量声明为let ,则只能在模块中重新分配(而不是用户)。 If it is changed, the import -ed variable changes accordingly. 如果更改,则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

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. 唯一的区别是,如果您尝试在此文件结束之前重新分配它。

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

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