JSFiddle - React, Tailwind, and code Playground
JavaScript
// This will be the object that holds your variables
let vars;
function executesMoreThanOnce(obj) {
const initVariables = function(obj) {
console.log('runs once and obj = ' + obj);
if (obj == undefined) {
console.log('initialize once');
const bools = {
boolOne: false,
boolTwo: false,
boolThree: false
};
const events = {
clickEvent:
function(event) {
//do stuff
},
keyEvent:
function(event) {
//do other stuff
}
};
return (function(){
return {bools: bools,
events: events};
})();
}
// If vars object, "which we passed as argument", is initialized once before just return it
return vars;
};
vars = initVariables(vars);
let booleanObject = vars.bools;
let 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.
// Yes you can now access the variables
booleanObject.boolOne = true;
}
//runs 5 times
for (let i=0; i<5; i++) {// Will execute 5 times
// Removed the bool flag and now passing the vars object as argument
executesMoreThanOnce(vars);
//executesMoreThanOnce();
//isVarsInitOnce = false;
}