【问题标题】:javascript: modifing an imported 'variable' causes 'Assignment to constant variable' even it is not a constantjavascript:修改导入的“变量”会导致“分配给常量变量”,即使它不是常量
【发布时间】:2019-05-12 09:23:08
【问题描述】:

我有两个文件,file1 导出一个变量 'not a constant' var x=1 和 file2 从中导入这个变量

问题是我无法修改导入的变量,即使它不是常量!

file1.js

export var x=1 //it is defined as a variable not a constant

file2.js

import {x} from 'file1.js'
console.log(x) //1
x=2 //Error: Assignment to constant variable

【问题讨论】:

    标签: javascript node.js ecmascript-6 es6-modules es6-module-loader


    【解决方案1】:

    这是the immutable exported module values 的效果。您可以使用同一模块中的另一个函数覆盖它

    在您的文件 1 中:

    export let x = 1;
    export function modifyX( value ) { x = value; }
    

    在你的文件中 2

    import { x, modifyX } from "file1.js"
    
    console.log( x ) // 1;
    modifyX( 2 );
    console.log( x ) // 2;
    

    【讨论】:

      猜你喜欢
      • 2021-03-10
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-28
      相关资源
      最近更新 更多