Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is IIFE required in the following context?

I am working to emulate the require functionality with a few javascript functions, for example:

// We set up an object that will include all the public modules
// And then a require function which basically just accesses that public module
const modules = {};
function require(moduleName) {
    return modules[moduleName];
}
modules['math.js'] = function() {
    // hidden implementation details
    let incr = x => ++x;
    return {
        incr, 
        sum(x,y) { return x+y; }
    }
}

Why is it required to do modules['math.js'] = (function() {...})(); and not just a normal non-invoked function call as above?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

modules["match.js"] is only a function. You probably want it to be an object:

modules["math.js"] = { ... };

But then you won’t have private members or functions you can use! Everything will be public. So to solve this we create a closure:

modules["math.js"] = function () {
    let priv = 0;

    return { ... };
};

Here’s where we are now. To make it a closure AND have modules["math.js"] be a nice object we can use, we immediately call this function:

modules["math.js"] = (function () {
    let priv = 0;

    return { ... };
})();

Now, modules["math.js"] is an object with members and methods we can use, AND it has a private locally scoped variable named priv that can be used only by the module.

This is similar to ES6 modules where you export a select few values bound to identifiers and everything else in the file is private.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading