I have been experimenting with the IIFE pattern for some of my modules lately and encountered a problem that has stumped me. In my current project, I need to pass a few global variables for usage. One of these is the global googletag variable which initially loads with a default state but changes once external code is loaded.
However, I noticed that it doesn't update because the pattern creates a copy instead of a reference. To simplify the issue, consider the example below.
window.globalLevel = 'First';
var Module = (function(_g){
function _stuff(){
return _g;
}
return {
get stuff(){
return _stuff();
}
}
})(window.globalLevel);
// Initial state.
console.log("In Module:", Module.stuff); // "First"
console.log("In Top:", window.globalLevel) // "First"
// After change.
console.log("--- Changing value ---")
window.globalLevel = 'Second'
console.log("In Module:", Module.stuff); // "First"
console.log("In Top:", window.globalLevel) // "Second"
Is there a way to resolve this? What adjustments or considerations should be made? Should I simply refer directly to window.globalReference in the module? It may seem messy, but it seems to work.