我正在使用 Webpack 作为打包器,但在任何地方都找不到我的问题的答案。
例如,我有文件 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'
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句