简体   繁体   English

Javascript,修改其他文件中的变量

[英]Javascript, modifying variables in other files

I have two files set up as such:我有两个文件这样设置:

file2.js文件2.js

var someVariable;

function setVariable(newVar){
    someVariable = newVar;
}

file1.js文件1.js

const file2Mod = require('./file2');

function initializeStuff(){
    .
    .
    .
    file2Mod.setVariable(4);
    .
    .
    .
}

For some reason, even after I call setVariable, the value of someVariable is still undefined.出于某种原因,即使在我调用 setVariable 之后,someVariable 的值仍然未定义。 I have tried printing the value of someVariable inside setVariable to the console before and after assignment, and it is successfully being assigned inside setVariable.我尝试在分配前后将 setVariable 中的 someVariable 的值打印到控制台,并且在 setVariable 中成功分配了它。 Somehow, this isn't translating when I try to access someVariable elsewhere in file1.js.不知何故,当我尝试访问 file1.js 中的 someVariable 时,这并没有翻译。 I am new to javascript, so I am probably making a silly mistake.我是 javascript 的新手,所以我可能犯了一个愚蠢的错误。 If more information is needed to solve the problem, I am happy to provide.如果需要更多信息来解决问题,我很乐意提供。 Any advice would be hugely appreciated!任何建议将不胜感激!

Thanks!谢谢!

EDIT:编辑:

I forgot to mention, I am exporting at the end of file2.js as such:我忘了提一下,我在 file2.js 的末尾这样导出:

exports.someVariable = someVariable
exports.setVariable = setVariable

window.someVariable = "abc" window.someVariable = "abc"

Try this.尝试这个。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM