Adding Modules to a Namespace using IIFE

25 Views Asked by At

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:

  1. Why does the function need a window as an argument?

  2. 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.

1

There are 1 best solutions below

0
Patrick On

Why does the function need a window as an argument?

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 window might not exist.

What does this variable declaration mean: var App = window.App || { };

If window.App exists, assign it to App, otherwise initialize App to an empty object {}.

why is it that at the bottom line there is a declaration: window.App = App

It assigns App (local) to window.App (global). Ensures modifications made to App inside the function are preserved in the global scope (not in the function).