简体   繁体   English

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

[英]How to change variable value from another module in javascript

I am using Webpack as bundler and I can't find answer to my question anywhere.我正在使用 Webpack 作为打包器,但在任何地方都找不到我的问题的答案。

For example, I have file index.js which contains:例如,我有文件 index.js,其中包含:

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

Func();
console.log(foo);

I have another file, let's say func.js which contains:我有另一个文件,假设 func.js 包含:

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

But it isn't possible to change value of variable from another module.但是不可能从另一个模块更改变量的值。

How do you handle such situations if I don't want to move function 'Func' to index.js?如果我不想将函数 'Func' 移动到 index.js,您如何处理这种情况?

I also know it is possible to mutate objects but using an object is not always an option.我也知道可以改变对象,但使用对象并不总是一种选择。

foo is a primitive. foo是一个原语。 You can't change it's the value assigned to it in the other module when it's a primitive, you can only change the value foo has been assigned in scope of the current module.当它是原语时,您不能更改它在另一个模块中分配给它的值,您只能更改在当前模块范围内分配的值foo

You could always do it with functions however:但是,您始终可以使用函数来做到这一点:

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从另一个文件更改 Javascript 变量值 - Change Javascript variable value from another file 如何在JavaScript中更改值而不保存到另一个变量 - How to change value in JavaScript without saving into another variable 从javascript中的另一个模块更新全局变量? - Update global variable from another module in javascript? 尝试从另一个JavaScript更改JavaScript变量 - Trying to change javascript variable from another javascript 如何从javascript中的模块导出具有aysnchronoulsy赋值的变量? - How to export a variable that has value assigned aysnchronoulsy from a module in javascript? Javascript:如何从另一个导入的模块内部访问导入的模块变量? - Javascript: How to access an imported module variable from inside another imported module? 如何将变量值放入 javascript 中的另一个变量中? - How to put variable value in another variable in javascript? 如何通过php从另一个页面获取javascript变量值 - How to get javascript variable value from another page by php function 如何从 JavaScript 中的另一个 function 访问变量值? - How one function access a variable value from another function in JavaScript? 如何从另一个网页更改javascript中的值? - How can you change a value in javascript from another webpage?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM