Change the value of imported variable in ES6

前端 未结 2 840
旧巷少年郎
旧巷少年郎 2020-12-30 21:12

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

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

export { a, b };

//m         


        
相关标签:
2条回答
  • 2020-12-30 21:45

    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;
    
    0 讨论(0)
  • 2020-12-30 22:03
    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 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 };
    

    with

    import { a, setA } from "./moduleA";
    
    setA(4);
    console.log(a); // 4
    

    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.

    0 讨论(0)
提交回复
热议问题