Javascript ES6 export const vs export let [英] Javascript ES6 export const vs export let
问题描述
export const a = 1;
vs
export let a = 1;
我了解 const
和 let
,但是当您输出它们时,有什么区别?
在ES6中, import
是导出值的实时只读视图。因此,当您执行从somemodule导入a;
时,无论如何,您不能分配到 a
在模块中声明 a
。
但是,由于导入的变量是直播视图,他们根据出口的原始出口变量进行变化。请考虑以下代码(从以下参考文献中借用):
// ------ lib.js - ----
export let counter = 3;
export function incCounter(){
counter ++;
}
// ------ main1.js ------
import {counter,incCounter} from'./lib';
//导入的值`counter`是live
console.log(counter); // 3
incCounter();
console.log(counter); // 4
//导入的值不能被更改
counter ++; // TypeError
正如你所看到的,区别在于 lib。 js
,而不是 main1.js
。
总结:
- 您无法分配到
import
-ed变量,无论你如何在模块中声明相应的变量。 - 传统的
让
-vs-const
语义适用于模块中声明的变量。
- 如果变量声明为
const
,则无法在任何地方重新分配或反弹。 >
- 如果变量声明为
let
,则只能在模块中重新分配(而不是用户)。如果更改,import
-ed变量相应地更改。
- 如果变量声明为
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?
In ES6, import
s are live read-only views on exported-values. As a result, when you do import a from "somemodule";
, you cannot assign to a
no matter how you declare a
in the module.
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
.
To summarize:
- You cannot assign to
import
-ed variables, no matter how you declare the corresponding variables in the module. - The traditional
let
-vs-const
semantics 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, theimport
-ed variable changes accordingly.
- If the variable is declared
这篇关于Javascript ES6 export const vs export let的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!