I was just learning the front-end, then I came up with a way to create a module using IIFE and register it to the namespace. From the code below, I still don't understand a few things:
Why does the function need a window as an argument?
What does this variable declaration mean:
var App = window.App || { };. And why is it that at the bottom line there is a declaration:window.App = App. What is the difference between the two declarations?
(function(window){
'use strict';
var App = window.App || {};
function DataStore(){
console.log('running the DataStore function');
}
App.DataStore = DataStore;
window.App = App;
}) (window);
I didn't understand the workflow of the function, and the site I visited didn't provide a detailed explanation. I hope you all can help me, thank you.
It ensures that the function has a reference to the global window object in scope (it doesn't have to use global scope).
Common pattern in JavaScript to pass globals into an IIFE. Also when running in environments where
windowmight not exist.If
window.Appexists, assign it toApp, otherwise initializeAppto an empty object{}.It assigns
App(local) towindow.App(global). Ensures modifications made toAppinside the function are preserved in the global scope (not in the function).