I am trying to reduce the global variables in my Chrome extension to reduce the 'spaghettiness' or ambiguity in my JavaScript.
I am trying to attempt this by having an init function that declares these otherwise global variables within a mousedown eventListener callback function that is likely to be fired more than once.
This is so that I can pass these variables + events through to other eventListener callbacks (namely a mouseup callback) as arguments of such callbacks.
I have decomposed the issue into a separate file:
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<script src="test.js"></script>
</body>
</html>
test.js
isVarsInitOnce = false;
function executesMoreThanOnce() {
const initVariables = function() {
console.log('runs once');
const bools = {
boolOne: false,
boolTwo: false,
boolThree: false
};
const events = {
clickEvent:
function(event) {
//do stuff
},
keyEvent:
function(event) {
//do other stuff
}
};
return {
bools: bools,
events: events
}
};
if (!isVarsInitOnce) {
isVarsInitOnce = true;
let vars = initVariables();
var booleanObject = vars.bools;
var eventObject = vars.events;
}
console.log('objects: ', booleanObject, eventObject);
//attempting to access initialised variable after function is executed more than once will cause an error.
//this is because the booleanObject is now undefined.
booleanObject.boolOne = true;
}
//runs twice
for (let i=0; i<2; i++) {
executesMoreThanOnce();
}
The method I have used to control the execution of the initVariables()
is a global boolean variable, isVarsInitOnce
which is effective at intialising the variables and setting the object for use in the executesMoreThanOnce()
function once.
The objects are able to be accessed in the first instance that the function is called in the for
loop, however the objects are undefined
when they are attempted to be accessed in the secondary instance that the function is called in the for
loop.
This is signified in rather clearly in the console output:
runs once
test.js:38 objects: {boolOne: false, boolTwo: false, boolThree: false} {clickEvent: ƒ, keyEvent: ƒ}
test.js:38 objects: undefined undefined //<--- (function called 2nd time)
test.js:42 Uncaught TypeError: Cannot set property 'boolOne' of undefined
at executesMoreThanOnce (test.js:42)
at test.js:47
I am unsure why this is occurring.
Can anyone help me to understand why this does not work properly?
Does anyone have a better suggestion for reducing global variables with regards to my case?
Many thanks.