javascript - 如何在javascript中更改另一个模块的变量值

标签 javascript webpack ecmascript-6

我使用 Webpack 作为 bundler ,但在任何地方都找不到我的问题的答案。

例如,我有文件index.js,其中包含:

import { Func } from './func.js'
export let foo = 'bar';

Func();
console.log(foo);

我还有另一个文件,比如说 func.js,其中包含:

import { foo } from './index.js';
export const Func = () => { foo = 'baz' }

但是不可能从另一个模块更改变量的值。

如果我不想将函数“Func”移动到index.js,您如何处理这种情况?

我也知道可以改变对象,但使用对象并不总是一种选择。

最佳答案

foo 是一个原语。当它是原语时,您无法更改在其他模块中分配给它的值,只能更改在当前模块范围内分配的值foo

但是,您始终可以使用函数来做到这一点:

let foo = 'initial value';

export const getFoo = () => foo;
export const setFoo = (val) => (foo = val);
import { getFoo, setFoo } from 'someModule';

getFoo(); // initial value;

// call this when necessary
setFoo('jim'); 
import { getFoo } from 'someModule';

// when called after `setFoo` has been called in the other module
getFoo(); // 'jim'

关于javascript - 如何在javascript中更改另一个模块的变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60712238/

相关文章:

javascript - 内联加载的 Web Worker 与 worker-loader 不工作

javascript - Firebase错误:Internal Given While Testing Callable Firebase Cloud Functions with Node Script

node.js - Webpack 构建成功但 npm webpack build 没有输出

javascript - 从 Angular 指令获取参数

javascript - babel loader 无法识别 React 应用程序中的 ES6 代码

javascript - 为什么当我使用 babel 将 ES6 编译为 ES5 时,浏览器需要一个 polyfills 文件

javascript - Axios 中数组 Promise 的链接

javascript - React 中表单元素的委托(delegate)

javascript - 在 HTML 文本区域上模拟 HTML 输入 "maxlength"属性的最佳方法是什么?

javascript - 诗农 spy 功能不起作用