简体   繁体   中英

Javascript, modifying variables in other files

I have two files set up as such:

file2.js

var someVariable;

function setVariable(newVar){
    someVariable = newVar;
}

file1.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. 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. Somehow, this isn't translating when I try to access someVariable elsewhere in file1.js. I am new to javascript, so I am probably making a silly mistake. 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:

exports.someVariable = someVariable
exports.setVariable = setVariable

window.someVariable = "abc"

Try this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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