在ES6中更改导入变量的值 [英] Change the value of imported variable in ES6

查看:748
本文介绍了在ES6中更改导入变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ES6模块,并将变量从moduleA导入到moduleB:

I'm using ES6 modules and am importing a variable from moduleA into moduleB:

//moduleA.js
let a = 5;
let b;

export { a, b };

//moduleB.js
import { a, b } from './moduleA'

a = 6;
b = 1;

但是在moduleB中进行更改/分配时,出现如下错误:

But on change/assignment in moduleB I'm getting error such as:

a = 6;

a = 6;

ReferenceError:未定义

ReferenceError: a is not defined

另一方面,我可以在moduleB中使用console.log(a).

On the other hand I can console.log(a) in 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?

推荐答案

import { a, b } from './moduleA'

类似于

const a = ...
const b = ...

,因为您以后无法分配该值.这并不完全相同,因为可以更改值 ,但是只能在模块的 中进行更改.所以你可以做

in that you cannot assign the value afterward. It's not quite the same because the values can change, but they can only be changed from inside the module. So you could do

let a = 5;
function setA(value) {
  a = value;
}

export { a, setA };

使用

import { a, setA } from "./moduleA";

setA(4);
console.log(a); // 4

从模块外部,您可以变异一个值,就像使用const一样,就像您要更改对象的属性一样,但是不能使变量指向一个完全不同的对象.

From outside of a module you can mutate a 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.

这篇关于在ES6中更改导入变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆