javascript 在 ES6 中更改导入变量的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48168601/
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
Change the value of imported variable in ES6
提问by croraf
I'm using ES6 modules and am importing a variable from moduleAinto moduleB:
我正在使用 ES6 模块并从moduleAinto导入一个变量moduleB:
//moduleA.js
let a = 5;
let b;
export { a, b };
//moduleB.js
import { a, b } from './moduleA'
a = 6;
b = 1;
But on change/assignment in moduleBI'm getting error such as:
但是在更改/分配中moduleB我收到错误,例如:
a = 6;
ReferenceError: a is not defined
一 = 6;
参考错误:a 未定义
On the other hand I can console.log(a)in moduleB.
另一方面,我可以console.log(a)在moduleB.
It seams it is not possible to assign to imported variables? Is this true or am I missing the way to do it? Why is this not possible?
它接缝不可能分配给导入的变量?这是真的还是我错过了这样做的方法?为什么这是不可能的?
回答by loganfsmyth
import { a, b } from './moduleA'
is similar to
类似于
const a = ...
const b = ...
in that you cannot assign the value afterward. It's not quite the same because the values canchange, but they can only be changed from insidethe module. So you could do
因为之后您不能分配该值。这并不完全相同,因为值可以更改,但它们只能从模块内部更改。所以你可以这样做
let a = 5;
function setA(value) {
a = value;
}
export { a, setA };
with
和
import { a, setA } from "./moduleA";
setA(4);
console.log(a); // 4
From outside of a module you can mutatea value, just like you could with const, like if you're changing a property on an object, but you cannot make the variable point to an entirely different object.
从模块外部,您可以改变一个值,就像使用 一样const,就像更改对象的属性一样,但不能使变量指向完全不同的对象。
回答by Troopers
You can use an object instead of variables, like this the reference doesn't change :
您可以使用对象而不是变量,像这样引用不会改变:
//moduleA.js
let object = {
a: 5,
};
export { object };
//moduleB.js
import { object } from './moduleA'
object.a = 6;
object.b = 1;

