Following up on What is file scope in javascript, from which I know that there might or might not be a so-called File Scope Variables, however, I do remember reading such term somewhere but couldn't find it any more, except the Q&A of What is file scope in javascript. Anyway,
I want to know what's exact behavior definition for such exported file scope variables.
Because I was trying to toggle my bot dynamically but wasn't able to, eliminating factors one by one, and it finally came down on me it is because of such "exported file scope variables", and me not understanding their behavior. Take a look at the following extremely simplified bot application:
VarTestFileA.js
function nextBot() {
BotC = !BotC
return BotA[BotC]
}
function logBot() {
console.log("I:", bot)
}
const BotA = {true: {"token": 2}, false: {"token":3}}
let BotC = true
var bot = BotA[BotC]
module.exports = {
bot,
nextBot,
logBot,
}
VarTestFileB.js
const bt = require('./VarTestFileA')
console.log(bt.bot)
bt.bot = bt.nextBot()
bt.logBot()
console.log("O:", bt.bot)
bt.bot = bt.nextBot()
bt.logBot()
console.log("O:", bt.bot)
bt.bot = bt.nextBot()
bt.logBot()
console.log("O:", bt.bot)
You may know (even without running it) that no matter how I did, the bt.bot
cannot be toggled. Here is the output:
$ node VarTestFileB.js
{ token: 2 }
I: { token: 2 }
O: { token: 3 }
I: { token: 2 }
O: { token: 2 }
I: { token: 2 }
O: { token: 3 }
Also, I tried to toggle bot
from within VarTestFileA.js
, it works within it, but console.log("O:", bt.bot.token)
never shows the updated value. All and all,
It all comes down to exact behavior definition of such exported file scope variables, because if putting them in the same file, it runs perfectly fine. Hence the question.