176

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 const and let, but when you export them, what are the differences?

4

2 回答 2

300

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

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

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

如您所见,区别实际上在于lib.js,而不是main1.js


总结一下:

  • import无论您如何在模块中声明相应的变量,都不能分配给-ed 变量。
  • 传统的let-vs-const语义适用于模块中声明的变量。
    • 如果声明了变量const,则不能在任何地方重新分配或重新分配它。
    • 如果声明了变量let,则只能在模块中重新分配(而不是用户)。如果它改变了,import-ed 变量也会相应地改变。

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

于 2015-09-14T07:04:54.623 回答
1

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

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

于 2015-09-14T07:00:45.350 回答