javascriptclosuresself-executing-function

Accessing constructor within an IIFE


Often, in JavaScript, I see an anonymous function, which is immediately invoked, that contains a constructor function. Something like this:

(function(){
    function Constructor{};
    //code and stuff
})();

This seems beneficial because it makes a Closure (?), so you can keep the variables within the function seperate from the Global Scope. What I'm having trouble understanding is how would I access this constructor from within the Global Scope. For instance, say the code above is contained in a JavaScript file which is brought into an HTML document with the script tag. Now, in the document (within another script tag) how can I instantiate an Object using the constructor in the anonymous function?


Solution

  • As you have stated, the main purpose of an immediately invoked function is to prevent the pollution of the Global scope. Therefore, all the variables and functions declared within an IIFE can only be accessed within that function.

    As I understand from your example, you are trying to modularize your application and separate your various application logic into different script files. I would recommend that you take a look at the Module Pattern:

    var Module1 = (function() {
    
        return {
            Constructor: function Constructor(){
                console.log('Hi, there!');
            }
        }
    })();
    

    Then, you could simply access the Constructor function using the following code:

    var test = Module1.Constructor();